我有这样的东西:
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/