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

一.原型链继承(prototype)函数

就是把要继承的方法写在原型链上性能

function Parent() {
    this.name = 'parent1';
    this.play = [1, 2, 3]
  }
  function Child() {
    this.type = 'child2';
  }
  Child.prototype = new Parent();

缺点:实例化的对象共用一个内存地址this

二.构造函数继承(call)prototype

function Parent(){
    this.name = 'parent1';
}

Parent.prototype.getName = function () {
    return this.name;
}

function Child(){
    Parent.call(this);
    this.type = 'child'
}

let child = new Child();
console.log(child);  // 没问题
console.log(child.getName());  // 会报错

可是只能继承父类的实例属性和方法,不能继承原型属性或者方法code

三.组合继承(手动挂上构造器,指向本身的构造函数)对象

function Parent3 () {
    this.name = 'parent3';
    this.play = [1, 2, 3];
}

Parent3.prototype.getName = function () {
    return this.name;
}

function Child3() {
// 第二次调用 Parent3()
    Parent3.call(this);
    this.type = 'child3';
}

// 手动挂上构造器,指向本身的构造函数
// 第一次调用 Parent3()
Child3.prototype = new Parent3();
Child3.prototype.constructor = Child3;

var s3 = new Child3();
var s4 = new Child3();
s3.play.push(4);
console.log(s3.play, s4.play);  // 不互相影响
console.log(s3.getName()); // 正常输出'parent3'
console.log(s4.getName()); // 正常输出'parent3'

缺点:形成了多构造一次的性能开销继承

相关文章
相关标签/搜索