问题描述
|
基本上,我有一个对象:
function tomatoe(name,owner) {
$(\'<div>\').click(this.squish).appendTo(myElement).text(\'I\\\'m a happy tomatoe called \' + name);
this.name = name;
this.dead = false;
this.owner = owner;
this.squish = function() {
console.log(\'Oh my Google,you killed \' + this.name + \'!\');
this.dead = true;
this.owner.sad = true;
};
}
该功能非常简单。实例化后,创建一个div,在其上附加一个点击处理程序,然后将其装订到某些东西上。实例化后,将传递两个参数:名称和所有者。所有者是对另一个对象的引用。
此代码有两个问题:
squish函数中的this引用已损坏,因为它现在引用了单击的元素。
由于链接的原因,当实际附加事件时,\“ this \”指的是jQuery或新创建的div元素(尚不确定哪个),因此this.squish是未定义的,并且从不调用。
如果有任何帮助,所有者对象将引用所有西红柿。
解决方法
您想将“ 1”重新分配给另一个变量,以免命名冲突。在实例化所有变量之后创建div也是一个好主意。
function tomatoe(name,owner) {
var that = this;
that.name = name;
that.dead = false;
that.owner = owner;
that.squish = function() {
console.log(\'Oh my Google,you killed \' + that.name + \'!\');
that.dead = true;
that.owner.sad = true;
};
$(\'<div>\').click(that.squish).appendTo(myElement).text(\'I\\\'m a happy tomatoe called \' + name);
}
,好吧,最简单的方法是创建一个本地变量来存储对tomatoe对象的引用,如下所示:
function tomatoe(name,owner) {
var _this = this;
$(\'<div>\').click(this.squish).appendTo(myElement).text(\'I\\\'m a happy tomatoe called \' + name);
this.name = name;
this.dead = false;
this.owner = owner;
this.squish = function() {
console.log(\'Oh my Google,you killed \' + _this.name + \'!\');
_this.dead = true;
_this.owner.sad = true;
};
}
,尝试这个:
function tomatoe(name,owner) {
//make a reference to this with self
var self = this;
$(\'<div>\').click(self.squish).appendTo(myElement).text(\'I\\\'m a happy tomatoe called \' + name);
this.name = name;
this.dead = false;
this.owner = owner;
this.squish = function() {
console.log(\'Oh my Google,you killed \' + this.name + \'!\');
this.dead = true;
this.owner.sad = true;
};
}
如果您想要可控制性,我该怎么办:
var tomato = {
name: null,dead: null,owner: null,init: function(name,owner){
var self = this;
$(\'<div>\').click(self.squish)
.appendTo(myElement).text(\'I\\\'m a happy tomatoe called \' + name);
this.name = name;
this.dead = false;
this.owner = owner;
return this;
},squish: function(){
console.log(\'Oh my Google,you killed \' + this.name + \'!\');
this.dead = true;
this.owner.sad = true;
return this;
}
}
//to instantiate it:
tomato.init(name,owner);
,您必须将jQuery行放在this.squish
赋值之后!显然,它是未定义的,除非您为其分配值。
function tomatoe(name,owner) {
var that = this;
this.name = name;
this.dead = false;
this.owner = owner;
this.squish = function() {
console.log(\'Oh my Google,you killed \' + that.name + \'!\');
that.dead = true;
that.owner.sad = true;
};
$(\'<div>\').click(this.squish).appendTo(myElement)
.text(\'I\\\'m a happy tomatoe called \' + name);
}