假设包含 jquery:
function FixedPoint(bgWidth) {
this.bgWidth= bgWidth;
this.plot();
$(window).resize(this.plot);
}
FixedPoint.prototype.plot = function() {
console.log(this.bgWidth); //This is undefined when called by resize
}
var pt1 = new FixedPoint(1920);
当在构造函数中调用 plot() 或初始化后一切正常,但是当 plot() 被调整大小函数调用时,它不能再通过 'this' 访问实例变量。
我可以在构造函数外调用 resize 来解决这个问题,但为了整洁起见,我想把它放在类中。
最佳答案
$(window).resize(this.plot);
从 window
上下文中调用方法 this.plot
。所以这是预期的行为。 this
将指向窗口对象而不是 FixedPoint
。您可以使用 Ecmascript5 function.bind显式绑定(bind)上下文。
$(window).resize(this.plot.bind(this));
通过 jquery,您可以使用 $.proxy做同样的事情。
只是为了提供更多信息,this
上下文是根据调用方法的位置设置的(绑定(bind)函数除外)。这里 this 会从窗口对象的 resize
方法中调用,其中 this
指的是窗口。
另一种 hacky 方法是使用匿名回调函数并使用缓存的 this 变量。
function FixedPoint(bgWidth) {
this.bgWidth = bgWidth;
var self = this; //cache it here
$(window).resize(function () {
self.plot(); //invoke with self.
});
}
关于javascript - jquery 调整大小丢失 'this' 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19014233/