(提取了一些隐藏在其他答案的评论中的解释)
问题在于以下行:
this.dom.addEventListener("click", self.onclick, false);
在这里,您传递一个函数对象以用作回调。当事件触发时,该函数被调用,但现在它与任何对象(this)都没有关联。
该问题可以通过将函数(及其对象引用)包装在闭包中来解决,如下所示:
this.dom.addEventListener(
"click",
function(event) {self.onclick(event)},
false);
因为变量 self 在创建闭包时被赋值,所以闭包函数会在以后调用时记住 self 变量的值。
解决这个问题的另一种方法是创建一个实用函数(并避免使用变量来绑定this):
function bind(scope, fn) {
return function () {
fn.apply(scope, arguments);
};
}
更新后的代码将如下所示:
this.dom.addEventListener("click", bind(this, this.onclick), false);
Function.prototype.bind
是 ECMAScript 5 的一部分并提供相同的功能。所以你可以这样做:
this.dom.addEventListener("click", this.onclick.bind(this), false);
对于还不支持 ES5 的浏览器,MDN 提供了以下 shim:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}