我创建了一个对象obj
:
function a(id, ...){
this.id = id;
......
}
var obj = new a("#somediv", ...);
我有这个功能:
a.prototype.b = function(){
$(this.id+" span").mouseover(function(){
$(this.id).addClass("c");
});
};
很明显,mouseover函数中的this
指向的是span
,而不是obj
……
我知道我可以通过创建一个变量并获取 this.id
的属性来解决这个问题,但是
有没有办法让mouseover函数中的this
指向obj
?
最佳答案
在较新的浏览器中使用纯 JavaScript,您可以绑定(bind)函数:
a.prototype.b = function(){
$(this.id+" span").mouseover(function(){
$(this.id).addClass("c");
}.bind(this));
};
使用 jQuery,您可以获得更好的浏览器支持:
a.prototype.b = function(){
$(this.id+" span").mouseover($.proxy(function(){
$(this.id).addClass("c");
}, this));
};
关于jQuery 中的 Javascript 'this' 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11380270/