1

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

 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

谢谢,

4

1 回答 1

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
}

thisincreateBlock函数应该与ofthis不同obj()。您还需要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
}
于 2013-02-25T06:09:34.567 回答