[英]How to share the same property for all classes that inherit from the parent
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 看一下我的代码简化代码: https : //codepen.io/anon/pen/wqRBYL?editors=0112
I have main Class called "Game". 我的主要班级叫做“游戏”。 Two next classes - "Coin" and "Monster" inherits from Game.
接下来的两个类-“硬币”和“怪物”从Game继承。
Game has this.coins property. 游戏具有this.coins属性。 When Coin will update this array I want to see it on Monster class.
当硬币将更新此数组时,我想在Monster类上看到它。 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: //编辑:来自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)
// 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.