すべてのクラスに同じプロパティを共有することに問題があります。私のコード簡略化されたコードで親から継承したすべてのクラスに対して同じプロパティを共有する方法
ルック:https://codepen.io/anon/pen/wqRBYL?editors=0112
は、私は「ゲーム」と呼ばれるメインクラスを持っています。次の2つのクラス - 「コイン」と「モンスター」はゲームから継承されます。
ゲームに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)
@Andreas。 – binariedMe
コインカウントを子供に分けてみるには、Game.prototype.coinのようなプロトタイプでゲームのインスタンスに関連付けられていないようにしておく必要があります。this.coin – binariedMe
共有価値をプロトタイプの下に保たない場合は、ゲームクラス(誰もがそれにアクセスできるので)ではなく私は2つの別々の方法を思いついた。私の[this](https://stackoverflow.com/a/35826569/4543207)の回答を見てください。 – Redu