Javascript 继承 - 使用对象创建

标签 javascript ecmascript-5

所以我正在尝试使用 Object.create()、Ecmascript 5!

我需要了解一些东西,因此我认为没有比这更好的地方了。

问题是为什么 Family #2 更改 Family #1 对象?!

代码

window.onload = function() {
     init();
}

function Family(surName) {
  this.surName = surName;
  this.meowMachine = 0;
  this.NameHistory = new Array();
  this.NameHistory[0] = surName;
}

function MakeFamily(familyToInherit, NewSurName, xMeows) {
  var newFam = Object.create(familyToInherit);
  newFam.surName = NewSurName;
  newFam.meowMachine += xMeows;
  newFam.NameHistory[0] = NewSurName;
  return newFam;
}

Family.prototype.myNameIs = function () {
  console.log('Family surname is: ' + this.surName);
}

Family.prototype.myHistoryIs = function() {

   for(var i = 0; i < this.NameHistory.length; i++)
   {
       console.log(this.NameHistory[i]);
   }    
} 

Family.prototype.XamountOfCats= function () {
  console.log('Familjen:' + this.surName + 
      ' Has a total number of cats: ' + this.meowMachine);
}

Family.prototype.ChangeSureName = function(surName) {
  this.NameHistory.push(surName);
  this.surName = surName;
}


function init() {
  //Instantiate Family #1 based on family base object
  var myFam1 = new Family("1# Family the:  Smiths");
  //Instantiate Family #2 based on Family #1 object
  var myFam2 = MakeFamily(myFam1,"2# Family the: Johnsons",2)
  //change the surName of Family #2
  myFam2.ChangeSureName("2# Family the: Simpsons");
  //Instantiate Family  #3 based on family base object
  var myFam3 = new Family("3# Family the: Akbars");
  console.log("------- Family #1 History -------");
  myFam1.myHistoryIs();
  console.log("------- Family #2 History -------");
  myFam2.myHistoryIs();
  console.log("------- Family #3 History -------");
  myFam3.myHistoryIs();
}

控制台 --> 输出

------- Family #1 History ------- 
2# Family the: Johnsons 
2# Family the: Simpsons 
------- Family #2 History ------- 
2# Family the: Johnsons 
2# Family the: Simpsons 
------- Family #3 History ------- 
3# Family the: Akbars 

我希望它的行为方式

    ------- Family #1 History ------- 
    1# Family the:  Smiths
    ------- Family #2 History ------- 
    2# Family the: Johnsons 
    2# Family the: Simpsons 
    ------- Family #3 History ------- 
    3# Family the: Akbars 

最佳答案

MakeFamily中,您必须使用

newFam.NameHistory = [NewSurName];

而不是

newFam.NameHistory[0] = NewSurName;

如果没有,您正在修改 familyToInheritNameHistory

关于Javascript 继承 - 使用对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23301336/

相关文章:

php - 如何在第一次按键时从数据库获取数据

javascript - TypeError : 'caller' , 'callee' 和 'arguments' 属性可能无法在严格模式函数或调用的参数对象上访问

javascript - 在元素的 ie11/Edge 中设置宽度 - 在严格模式下不允许分配给只读属性

javascript - Highcharts 单击列(不是栏)

javascript - 如何实现使用 Angular 6 创建的表格左侧的复选框?

javascript - 用 ECMAScript 重写 AngularJS 2.0?

javascript - ES5 中 Object.freeze 的效果可以逆转吗?

javascript - 为什么在 JavaScript 库中使用 `strict mode`?

javascript - 无法在 jquery-confirm 中设置宽度?

javascript - 简单验证也不起作用