2017-08-30 88 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