基本上,我有一个对象:
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,将一个单击处理程序附加到它,然后将其装订到某个东西上。在实例化时,传递两个参数:名称和所有者。所有者是对另一个对象的引用。
此代码存在两个问题:
如果它有任何帮助,所有者对象可以引用所有西红柿。
答案 0 :(得分:1)
试试这个:
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);
答案 1 :(得分:1)
您必须在this.squish
作业之后放置jQuery行!在您为其指定值之前,它显然是未定义的。
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);
}
答案 2 :(得分:1)
嗯,做你想做的最简单的方法是创建一个局部变量来存储对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;
};
}
答案 3 :(得分:1)
您希望将this
重新分配给另一个变量,以便命名不会发生冲突。在实例化所有变量后创建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);
}