我有一个像下面的对象
function obj() {
this.cellSize = 50;
this.createBlock = function() { // creates a block object
this.x = 0;
this.y = 0 - (this.cellSize * 1.5);
this.baseVelocity = 1;
this.velocity = this.baseVelocity;
return this;
};
this.activeBlock = this.createBlock(); // active block object
this.nextBlock = this.createBlock(); // next block object
}
当我检查obj.activeBlock
时,我没有收到应该从obj.createBlock
返回的对象?
谢谢,
答案 0 :(得分:2)
您可能需要以下内容:
function obj() {
var that = this;
this.cellSize = 50;
this.createBlock = function() { // creates a block object
this.x = 0;
this.y = 0 - (that.cellSize * 1.5);
this.baseVelocity = 1;
this.velocity = this.baseVelocity;
return this;
};
this.activeBlock = new this.createBlock(); // active block object
this.nextBlock = new this.createBlock(); // next block object
}
this
函数中的createBlock
应与this
的{{1}}不同。您还需要使用obj()
为每个块创建一个新对象。如果new
应该是常量,则可以将代码重写为闭包:
cellSize