Javascript';这';jQuery中的指针

Javascript';这';jQuery中的指针,javascript,pointers,this,Javascript,Pointers,This,我创建了一个对象obj: function a(id, ...){ this.id = id; ...... } var obj=newa(“#somediv”,…) 我有这个功能: a.prototype.b = function(){ $(this.id+" span").mouseover(function(){ $(this.id).addClass("c"); }); }; a.prototype.b = function(){

我创建了一个对象
obj

function a(id, ...){
   this.id = id;
   ......
}
var obj=newa(“#somediv”,…)

我有这个功能:

a.prototype.b = function(){
    $(this.id+" span").mouseover(function(){
        $(this.id).addClass("c");
    });

};
a.prototype.b = function(){
    $(this.id+" span").mouseover(function(){
        $(this.id).addClass("c");
    }.bind(this));
};
显然,mouseover函数中的
this
指向
span
,而不是
obj

我知道我可以通过创建一个变量并获取this.id的属性来解决这个问题,但是


有没有办法让鼠标上方函数中的
this
指向
obj
呢?

在较新的浏览器中,使用纯JavaScript,可以绑定函数:

a.prototype.b = function(){
    $(this.id+" span").mouseover(function(){
        $(this.id).addClass("c");
    });

};
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));
};

使用
$代理的备选方案

a.prototype.b = function(){
    $(this.id+" span").mouseover($.proxy(function(){
        $(this.id).addClass("c");
    }, this));
};

请注意,JS没有指针,至少在传统意义上没有,例如C。(您不能执行任何类型的指针算术,您可以将引用作为参数传递,但不能更新原始变量引用的对象,等等)作为关于
bind
vs
proxy
foo.bind(bar)!=foo.bind(bar)
,这意味着如果要删除事件处理程序,需要存储对绑定函数的引用,但是如果使用jQuery的
$.proxy
,jQuery能够解除绑定函数的“相同”代理(
$.proxy(foo,bar)!==$.proxy(foo,bar)
,但是返回的函数将有一个GUID,jQuery可以使用它来匹配同一函数的代理)。