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

时间:2013-02-25 06:01:34

标签: javascript object

我有一个像下面的对象

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

谢谢,

1 个答案:

答案 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