2017-08-30 89 views
0

我有與所有類共享相同的屬性的問題。如何爲從父項繼承的所有類共享相同的屬性

看我的代碼簡化代碼:https://codepen.io/anon/pen/wqRBYL?editors=0112

我有所謂的「遊戲」主類。接下來的兩堂課 - 「錢幣」和「怪物」從遊戲中繼承。

遊戲中有this.coins屬性。當Coin將更新這個數組時,我想在Monster類中看到它。我應該如何寫它?

// console.log 
"Game object: " [1, 2, 3, 4, 5, 6] 
"Coin object: " [1, 2, 3, 4, 5, 6, 7, 8] 
"Monster object: " [1] 
"Game object: " [1] 
"---------" 

我該如何防止雙重遊戲日誌?

//編輯:代碼從CodePen:

// Main Class. 
function Game() { 

    this.coins = [1]; // I want to share this array between all classes that inherit from the Game 

    var self = this; 

    setInterval(function() { 
    console.log('Game object: ', self.coins) // Correctly shows values thar Coin class is adding. 
    }, 5000) 


} 

//Inherits from Game. 
function Monster() { 

    Game.call(this); 

    var self = this; 

    setInterval(function() { 
    console.log('Monster object: ', self.coins); // Always show first state of Game's array - [1] 
    }, 5000) 

} 

Monster.prototype = Object.create(Game.prototype); 
Monster.prototype.constructor = Monster; 

//Inherits from Game. 
function Coin() { 

    Game.call(this); 

    var self = this, 
     newCoin = 2; 

    setInterval(function() { 
    self.coins.push(newCoin++) 
    console.log('Coin object: ', self.coins); // Correctly returns more and more. 
    }, 5000) 

} 

Coin.prototype = Object.create(Game.prototype); 
Coin.prototype.constructor = Coin; 

new Coin(); 
new Monster(); 

setInterval(function() { 
    console.log('---------'); 
}, 5000) 
+0

@Andreas我相信這並不需要更多的解釋。 – binariedMe

+0

看到分享硬幣數給孩子,你必須保持它的原型像Game.prototype.coin,而不是通過這樣做與遊戲的實例相關聯:this.coin – binariedMe

+0

如果你想保持共享價值不在原型的遊戲類(因爲每個人都可以訪問它)但是私有的,然後我想出了兩種不同的方式。看看[this](https://stackoverflow.com/a/35826569/4543207)我的答案。 – Redu

回答

0
// Main Class. 
function Game(options) { 
inherit from the Game 

    var self = this; 

    setInterval(function() { 
    console.log('Game object: ', self.coins) // Correctly shows values thar Coin class is adding. 
    }, 5000) 


} 
Game.prototype.coin = 0; // this will be shared across Game and its children's instances. 
//Inherits from Game. 
function Monster() { 

    Game.call(this); 

    var self = this; 

    setInterval(function() { 
    console.log('Monster object: ', self.coins); // Always show first state of Game's array - [1] 
    }, 5000) 

} 

Monster.prototype = Object.create(Game.prototype); 
Monster.prototype.constructor = Monster; 

//Inherits from Game. 
function Coin() { 

    Game.call(this); 

    var self = this, 
     newCoin = 2; 

    setInterval(function() { 
    self.coins.push(newCoin++) 
    console.log('Coin object: ', self.coins); // Correctly returns more and more. 
    }, 5000) 

} 

Coin.prototype = Object.create(Game.prototype); 
Coin.prototype.constructor = Coin; 

new Coin(); 
new Monster(); 

setInterval(function() { 
    console.log('---------'); 
}, 5000) 
+0

當然,我必須將它添加到原型。它的工作原理,謝謝! :) – michalgrzasko