gpt4 book ai didi

javascript - 如何从对象函数返回对象 - javascript?

转载 作者:行者123 更新时间:2023-11-30 18:09:12 26 4
gpt4 key购买 nike

我有一个像下面这样的对象

 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 返回的对象?

谢谢,

最佳答案

你可能想要这样的东西:

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
}

createBlock函数中的this应该和obj()this不同。您还需要为每个 block 使用 new 创建一个新对象。如果 cellSize 应该是一个常量,您可以将代码重写为闭包:

function obj() {
var cellSize = 50;

this.createBlock = function() { // creates a block object
this.x = 0;
this.y = 0 - (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
}

关于javascript - 如何从对象函数返回对象 - javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15060999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com