gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:05:10 26 4
gpt4 key购买 nike

我试图通过继承 pixi.js 的 PIXI.Container 对象来创建一个新对象。 PIXI.Container 对象具有属性 height 和 width,我想从构造函数的参数中设置它们。每次我尝试这样做时,“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;

按照要求进行了编辑。

此外,这里还有代码工作演示的链接以及 github 存储库的链接

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;
}
}
});

关于javascript - 如何在 JavaScript 的构造函数中重写继承对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30391505/

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