[英]jquery resize loses 'this' reference
假設包括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()時,一切正常,但是當resize函數調用plot()時,它不再可以通過'this'訪問實例變量。
我可以在構造函數的外部調用resize來解決此問題,但為了使其整潔,希望將其放在類中。
$(window).resize(this.plot);
從window
上下文中調用this.plot
方法。 因此,這是預期的行為。 this
將指向窗口對象,而不是FixedPoint
。 您可以使用Ecmascript5 function.bind顯式綁定上下文。
$(window).resize(this.plot.bind(this));
使用jquery,您可以使用$ .proxy來執行相同的操作。
為了提供更多的見解,根據調用方法的位置(綁定函數除外)設置this
上下文。 下面這一切都得到了來自內部調用resize
窗口對象,其中的方法, this
是指窗口。
另一種駭人聽聞的方法是使用匿名回調函數並使用緩存的此變量。
function FixedPoint(bgWidth) {
this.bgWidth = bgWidth;
var self = this; //cache it here
$(window).resize(function () {
self.plot(); //invoke with self.
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.