javascript - jquery 调整大小丢失 'this' 引用

标签 javascript jquery

假设包含 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/

相关文章:

javascript - 从表中的 <th> 中删除属性

javascript - 关闭模态后页面变暗无法上下滚动

javascript - AngularJS 的延期 promise

javascript - p5.j​​s 中的未知 'transpose3x3' 错误?

php - 将关联数组值获取到变量中,这是来自 cookie 的字符串格式

javascript - 使用 groupBy 进行多次 ng-repeat

javascript - 图片翻转效果不适用于 Safari 和 IE

javascript - ajax调用后替换类名

javascript - 使用 PHP 记录集数据的 Bootstrap 3 Modal

jquery - 如何防止覆盖 jQuery 的 $.ajaxSetup() 选项?