本文介绍了我如何在jQuery中保留'this'的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的东西:
var Something = function(){
this.render = function(){};
$(window).resize(function(){
this.render();
});
}
麻烦在于,匿名函数"this"内部引用了窗口对象.我知道我可以做类似的事情:
The trouble is that inside the anonymous function 'this' refers to the window object. I know I could do something like:
var Something = function(){
this.render = function(){};
var tempThis = this;
$(window).resize(function(){
tempThis.render();
});
}
但是有更好的方法吗?这看起来不太优雅.
but is there a better way? This doesn't look very elegant.
推荐答案
您找到的解决方案是大多数人使用的解决方案.常见的约定是将您的tempThis变量称为"that".
The solution you found is the the one most people use. The common convention is to call your tempThis variable "that."
var Something = function(){
this.render = function(){};
var that = this;
$(window).resize(function(){
that.render();
});
};
这篇关于我如何在jQuery中保留'this'的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!