jQuery中的Javascript'this'指针

3 javascript pointers this

我创建了一个对象obj:

function a(id, ...){
   this.id = id;
   ......
}
Run Code Online (Sandbox Code Playgroud)

var obj = new a("#somediv", ...);

我有这个功能:

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

};
Run Code Online (Sandbox Code Playgroud)

显然,this鼠标悬停功能指向span而不是obj......

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

有没有办法让this鼠标悬停功能指向obj

ick*_*fay 5

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

a.prototype.b = function(){
    $(this.id+" span").mouseover(function(){
        $(this.id).addClass("c");
    }.bind(this));
};
Run Code Online (Sandbox Code Playgroud)

使用jQuery,您可以获得更好的浏览器支持:

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

  • 关于`bind` vs`source`,`foo.bind(bar)!== foo.bind(bar)`的说明,这意味着如果你想删除它,你需要存储对绑定函数的引用事件处理程序,但是如果你使用jQuery的`$ .proxy`,jQuery能够取消绑定函数的"相同"代理(`$ .proxy(foo,bar)!== $ .proxy(foo,bar)`,但是返回的函数将有一个GUID,jQuery可以使用它来匹配相同函数的代理). (3认同)