我有这样的东西:
var Tset = function(){
this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
$(this.a).mouseover(function(){
this.setBackground('red');
});
this.setBackground = function(_color){
$(this.a).css({'background-color':'color'});
}
}
var x = new Tset();
我的问题是我无法从 mouseover
回调函数调用 this.setBackground
。我怎么解决这个问题?
谢谢!
最佳答案
是的,在回调中 this
指的是元素而不是实例的上下文。所以尝试缓存this
。
var Tset = function () {
var self = this; //<-- cache this to be used later
this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
$(this.a).mouseover(function () {
self.setBackground('red'); //invoke it with self
});
this.setBackground = function (_color) {
$(this.a).css({
'background-color': _color
});
}
}
var x = new Tset();
还有其他与此类似的可用技术,它们使用 Ecmascript5 function.bind , $.proxy等等
使用绑定(bind)函数:
var Tset = function () {
this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
$(this.a).mouseover((function () {
this.setBackground('red'); //Now this will be your instanc's context
}).bind(this)); //bind the context explicitly
this.setBackground = function (_color) {
$(this.a).css({
'background-color': _color
});
}
}
除了绑定(bind)函数之外,调用者决定回调内的上下文
<强> Fiddle
关于javascript - 从回调函数中调用其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19119286/