jQuery 中的 Javascript 'this' 指针

标签 javascript pointers this

我创建了一个对象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/

相关文章:

javascript - 使用 lodash 的递归循环

javascript - 如何使用 "set"方法设置新属性

c++ - 带指针的模板类的析构函数

c++ - 在 C++ 中,如何对提供指针的函数返回的值进行操作?

c++ - 自定义弱/强引用指针

c++ - 参数和成员变量同名不好吗?

javascript - React JS : Function undefined when called in . map 函数

javascript - 每个类都需要 JSHint 全局变量中的一个条目吗?

javascript - 如何在对象的另一个键中使用一个键的值?

javascript - 在 React 中使用 Map 与 firebase