我在我的Javascript代码中使用这个基本事件系统,并且正在尝试为我的同事记录它。我不确定这段代码中的“范围”和“上下文”有什么区别。任何人都可以帮助我理解为什么我甚至需要它们两个?在此Javascript代码中的“范围”和“上下文”中有所不同
this.myClass.prototype.on = function (type, method, scope, context) {
var listeners, handlers, scope;
if (!(listeners = this.listeners)) {
listeners = this.listeners = {};
}
if (!(handlers = listeners[type])) {
handlers = listeners[type] = [];
}
scope = (scope ? scope : window);
handlers.push({
method: method,
scope: scope,
context: (context ? context : scope)
});
}
this.myClass.prototype.trigger = function(type, data, context) {
var listeners, handlers, i, n, handler, scope;
if (!(listeners = this.listeners)) {
return;
}
if (!(handlers = listeners[type])){
return;
}
for (i = 0, n = handlers.length; i < n; i++){
handler = handlers[i];
if (context && context !== handler.context) continue;
if (handler.method.call(
handler.scope, this, type, data
)===false) {
return false;
}
}
return true;
}
所以基本上,范围是没有意义的,就像我想的那样。我希望我能记住我在哪里找到这个代码。 –
对于ES6中的'let'和'const',现在有一个块范围很好。有人请纠正我,如果我错了。 – khizar