我有这样的事情:
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();
Run Code Online (Sandbox Code Playgroud)
我的问题是我无法this.setBackground从mouseover回调函数调用.我怎么解决这个问题?谢谢!
是的,回调内部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();
Run Code Online (Sandbox Code Playgroud)
还有其他类似的技术,使用Ecmascript5 function.bind,$ .proxy等.
使用绑定功能:
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
});
}
}
Run Code Online (Sandbox Code Playgroud)
除了绑定函数,调用者确定回调内的上下文
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |