如何在 javascript 的构造函数中覆盖继承对象的 属性?

How can I override an inherited object's property in the constructor in javascript?

我正在尝试通过继承 pixi.js 的 PIXI.Container 对象来创建新对象。 PIXI.Container 对象具有高度和宽度属性,我想从我的构造函数的参数中设置它们。每次我尝试这样做时,'this.height' 参数始终为 0。

我很困惑!

var Chunk = function(data) {

console.log(data);

/*
*   Outputs:
*   Object {
*     "_id": "555f7939c3ae58523f63b847",
*     "x": 2,
*     "y": 2,
*     "height": 2000,
*     "width": 2000,
*     "__v": 0,
*     "layers": [
*       {
*         "name": "collision",
*         "height": 2000,
*         "width": 2000,
*         "opacity": 1,
*         "visible": true,
*         "type": "objectgroup",
*         "objects": []
*       }
*     ]
*   }
*/

PIXI.Container.call(this);

console.log(this);

/*
*   Outputs:
*   Couldn't copy the object, but i've included a link to a working
*   demo where you can see it output. https://vast-wildwood-6251.herokuapp.com/
*/

this.height = data.height;
this._width = data.width;
this.coords = {
    x: data.x,
    y: data.y
};
this.x = data.x * this._width;
this.y = data.y * this.height;
console.log(this.height); // Outputs: 0
this.planets = [];

var border = new PIXI.Graphics();
border.lineStyle(2, 0xFF0000, 1);
border.drawRect(this.x, this.y, this.width, this.height);
this.addChild(border);

for (var c = 0; c < data.layers.length; c++) {
    for (var o = 0; o < data.layers[c].objects.length; o++) {
        var planet = new Planet(data.layers[c].objects[o]);
        game.planets.push(planet);
        this.planets.push(planet);
        this.addChild(planet.graphics);
    }
}

};

Chunk.prototype = Object.create(PIXI.Container.prototype);

Chunk.prototype.constructor = Chunk;

按要求进行了编辑。

另外,这里有一个 link 代码的工作演示,还有一个 link 到 github repo

https://vast-wildwood-6251.herokuapp.com/ https://github.com/storrdev/delta-wing

PIXI.Container 的代码对 height 属性 使用了 setter。因此,您不能直接设置它。参见 https://github.com/GoodBoyDigital/pixi.js/blob/master/src/core/display/Container.js#L78

Object.defineProperties(Container.prototype, {    
    /**
     * The height of the Container, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     * @memberof PIXI.Container#
     */
    height: {
        get: function ()
        {
            return  this.scale.y * this.getLocalBounds().height;
        },
        set: function (value)
        {

            var height = this.getLocalBounds().height;

            if (height !== 0)
            {
                this.scale.y = value / height ;
            }
            else
            {
                this.scale.y = 1;
            }

            this._height = value;
        }
    }
});