我已经遇到过几次了。我试图创建最简单的代码片段来演示它。
问题是,在内部和对象方法中,如果我将匿名函数传递给 jQuery 方法(如“each”),在函数内部,我将无法访问对象的“this”。因为“this”现在与 jQuery 对象相关。
logNameAndElementIds
问题的症结见方法中间的注释:
(我正在使用 Crockford 的对象函数来生成基于对象字面量定义的对象的对象实例。)
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
var objectLiteral = {
setName: function(name){
this.name = name;
},
logNameAndElementIds: function(){
// works fine, 'this' refers to object instance
console.log( this.name );
$('.foo').each(function(){
// we've lost "this" because it now refers to jQuery
console.log( this.name );
console.log( $(this).attr('id') );
});
}
};
obj1 = Object.create(objectLiteral);
obj1.setName('Mike');
obj1.logNameAndElementIds();
处理或解决这种情况的正确方法是什么?
显然我的例子很愚蠢,但这只是为了证明一个观点。更多时候我想循环一个 jQuery 匹配集,然后在每个项目上调用包含对象的方法。但我无法访问对象的方法,因为我现在有 jQuery 的“this”。