I have problem with sharing the same property to all classes.
Look at my code simplified code: https://codepen.io/anon/pen/wqRBYL?editors=0112
I have main Class called "Game". Two next classes - "Coin" and "Monster" inherits from Game.
Game has this.coins property. When Coin will update this array I want to see it on Monster class. How should I write it?
// 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]
"---------"
And how can I prevent double Game log?
// edit: Code from 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)