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

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

本文关键字:继承 对象 属性 重写 构造函数 javascript      更新时间:2023-09-26

我试图通过继承PIXI. js的PIXI来创建一个新的对象。容器对象。对PIXI。容器对象具有高度和宽度的属性,我想从构造函数的参数中设置。每次我想这么做的时候,"这个。"高度"参数始终为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;

按要求编辑。

此外,这里有一个链接到代码的工作演示,以及一个链接到github的repo

https://vast 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;
        }
    }
});