[英]How can I set a default property for an object that's passed into a constructor?
[英]How can I override an inherited object's property in the constructor in javascript?
我正在嘗試通過繼承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;
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.