每日灵魂一问-继承的6种方法(下)

Posted NANA

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每日灵魂一问-继承的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

以上是关于每日灵魂一问-继承的6种方法(下)的主要内容,如果未能解决你的问题,请参考以下文章

node.js每日灵魂一问- node.js的fs模块&常用方法

每日灵魂一问- Node 中 Buffer 的理解

每日灵魂一问-对WebSocket的理解?应用场景?

每日灵魂一问-Nodejs文件查找的优先级&Require 方法的文件查找策略?

每日灵魂一问-关于react

每日灵魂一问-如何实现文件上传?