乐趣区

关于javascript:每日灵魂一问继承的6种方法下

四. 原型式继承(Object.create)

let parent4 = {
    name: "parent4",
    friends: ["p1", "p2", "p3"],
    getName: function() {return this.name;}
  };

  let person4 = Object.create(parent4);
  person4.name = "tom";
  person4.friends.push("jerry");

  let person5 = Object.create(parent4);
  person5.friends.push("lucy");

  console.log(person4.name); // tom
  console.log(person4.name === person4.getName()); // true
  console.log(person5.name); // parent4
  console.log(person4.friends); // ["p1", "p2", "p3","jerry","lucy"]
  console.log(person5.friends); // ["p1", "p2", "p3","jerry","lucy"]

毛病 :浅拷贝,多个实例的援用类型属性指向雷同的内存

五. 寄生式继承

let parent5 = {
    name: "parent5",
    friends: ["p1", "p2", "p3"],
    getName: function() {return this.name;}
};

function clone(original) {let clone = Object.create(original);
    clone.getFriends = function() {return this.friends;};
    return clone;
}

let person5 = clone(parent5);
let person6 = clone(parent5);

person5.name = '22';
person5.friends.push(22);
console.log(person5.getName()); // parent5
console.log(person5.getFriends()); // ["p1", "p2", "p3", 22]
console.log(person6.getName()); // parent5
console.log(person6.getFriends()); // ["p1", "p2", "p3", 22]

毛病 :浅拷贝,多个实例的援用类型属性指向雷同的内存

六. 寄生组合式继承 (全场最佳)

function clone (parent, child) {
    // 这里改用 Object.create 就能够缩小组合继承中多进行一次结构的过程
    child.prototype = Object.create(parent.prototype);
    child.prototype.constructor = child;
}

function Parent6() {
    this.name = 'parent6';
    this.play = [1, 2, 3];
}
Parent6.prototype.getName = function () {return this.name;}
function Child6() {Parent6.call(this);
    this.friends = 'child5';
}

clone(Parent6, Child6);

Child6.prototype.getFriends = function () {return this.friends;}

let person6 = new Child6(); 
console.log(person6); //{friends:"child5",name:"child5",play:[1,2,3],__proto__:Parent6}
console.log(person6.getName()); // parent6
console.log(person6.getFriends()); // child5
退出移动版