簡體   English   中英

無法實例化 class 並將其添加到數組中 - object 屬性始終為 0?

[英]Trouble instantiating class and adding it to an array - object properties are always 0?

為什么無論我在let $newTileData = new tile([1,3],{})中輸入什么值, coords總是0,0

 class tile { constructor(coords, layers) { this.coords = [0, 0]; this.layers = [ {sprite: ""}, {sprite: ""}, {sprite: ""}, //player "layer" is here? {sprite: ""}, {sprite: ""}, {sprite: ""} ] } } let mapdata = { mapName: "Test", tiles: [ ] }; let $newTileData = new tile([1,3],{}) mapdata.tiles.push($newTileData); console.log(mapdata);

無論您為值添加什么, coords始終為 0,0,因為您聲明: this.coords = [0, 0]; 在 class 中。 當你這樣做時,你忽略了輸入值。 與忽略layers相同:

this.layers =
        [
            {sprite: ""},
            {sprite: ""},
            {sprite: ""},
            //player "layer" is here?
            {sprite: ""},
            {sprite: ""},
            {sprite: ""}
        ]
//Now the function(layers) doesn't do anything because layers is ignored.

您需要一個實際使用構造函數參數而不是僅設置默認值的構造函數。 如果需要保留默認值(以保持工作的空構造函數new tile() ),則可以添加代碼來適應它。

// this would need to be used with values, new title([0,0], {layerdata})
class tile {
    constructor(coords, layers) {
        this.coords = coords;
        this.layers = layers;
    }
}

這符合我的想法......感謝@quicVO 引導我做到這一點。

let $newTileCoords = [1,3];
let $newTileData = new tile()
$newTileData.coords = $newTileCoords;
mapdata.tiles.push($newTileData);

如果有人想出一種更合適的方法來實例化具有值的 class ,將不予回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM