javascript - 如何在 jquery 中保留 'this' 的上下文

标签 javascript jquery this

我有这样的东西:

var Something = function(){
  this.render = function(){};
  $(window).resize(function(){
    this.render();
  });
}

问题是在匿名函数内部'this'引用了window对象。我知道我可以做类似的事情:

var Something = function(){
  this.render = function(){};
  var tempThis = this;
  $(window).resize(function(){
    tempThis.render();
  });
}

但是有更好的方法吗?这看起来不太优雅。

最佳答案

您找到的解决方案是大多数人使用的解决方案。通常的约定是将您的 tempThis 变量称为“that”。

var Something = function(){
  this.render = function(){};
  var that = this;
  $(window).resize(function(){
    that.render();
  });
};

关于javascript - 如何在 jquery 中保留 'this' 的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1043556/

相关文章:

javascript - 实现 github.com 文件无缝文件导航

javascript - worker 、网络或服务;无论如何要访问窗口对象?

php - 如何在 jQuery.knob 中添加值后缀

javascript - * 选择器上绑定(bind)单击事件时多次执行

javascript - if(this) {} else {} 是否曾经访问过 JavaScript 中的 else?

javascript - typescript : fat arrow & this scope relation

javascript - 如何使用 jQuery 从 URL 中仅获取 Controller 名称和操作名称

javascript - WebStorm 无法识别某些 Angular 组件 - mat-toolbar 未知元素

javascript - 如何使用 jquery 在我的 img src 上添加路径?

javascript - 对 'this' 的内部引用未在返回对象中解析