如何为从父级继承的所有类共享相同的属性

时间:2017-08-30 15:53:58

标签: javascript oop object inheritance

我在向所有类共享相同属性时遇到问题。

查看我的代码简化代码:https://codepen.io/anon/pen/wqRBYL?editors=0112

我有一个名为" Game"的主要课程。接下来的两个课程 - " Coin"和"怪物"继承自游戏。

游戏有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)

1 个答案:

答案 0 :(得分: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)