玩命加载中 . . .

原型链的继承


前言

Q:什么是原型继承?
A:一个对象可以使用另外一个对象的属性或者方法,就称之为继承。具体是通过将这个对象的原型设置为另外一个对象,这样根据原型链的规则,如果查找一个对象属性且在自身不存在时,就会查找另外一个对象,相当于一个对象可以使用另外一个对象的属性和方法了。

下面看看原型链的六种继承方式。

原型链继承

  • 模拟实现:
    function Parent() {
        this.name = ['siyang', 'hcy'];
    }
    Parent.prototype.getName = function() {
        console.log(this.name);
    }
    function child() {}
    child.prototype = new Parent();
    var son = new child();
    son.getName(); // ["siyang", "hcy"]
    son.name.push('hg');
    console.log(son.name); // ["siyang", "hcy", "hg"]
    
    var sis = new child();
    sis.getName(); // ["siyang", "hcy", "hg"]
    console.log(sis.name); // ["siyang", "hcy", "hg"]

    借用构造函数(经典继承)

  • 模拟实现:
    function Parent(name) {
        this.name = name;
    }
    function Child(name) {
        Parent.call(this, name);
    }
    
    var child1 = new Child('kevin');
    console.log(child1.name); // kevin
    var child2 = new Child('daisy');
    console.log(child2.name); // daisy
  • 优点:
    • 避免了引用类型的属性被所有实例共享:关键在于this指向(call 实现);
    • 可以在子构造函数中向父构造函数传参。
  • 缺点:由于必须在构造函数中定义方法,因此函数不能重用。

    组合继承(伪经典继承)(原型链继承+经典继承)

    使用原型链实现对原型属性和方法的继承,通过借用构造函数实现对实例属性的继承。
  • 模拟实现:
    function Parent(name) {
        this.name = name;
        this.color = ['blue'];
    }
    function child(name, age) {
        Parent.call(this, name);
        this.age = age;
    }
    child.prototype = new Parent();
    
    var son = new child('hcy','20');
    son.color.push('red');
    console.log(son.name); // hcy
    console.log(son.age); // 20
    console.log(son.color); // ["blue", "red"]
    
    var sister = new child('hg');
    console.log(sister.color); // ["blue"]
  • 优点:融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。而且 instanceofisPrototypeof() 也能够用于识别基于组合继承创建的对象。
  • 缺点:会调用两次父构造函数。一次是设置子类型实例的原型的时候:child.prototype = new Parent() ;另一次在创建子类型实例的时候:var son = new child('hcy','20')

    原型式继承

    借助原型可以基于已有的对象创建新的对象,同时还不必因此创建自定义的类型。于是有了下面这个函数。
    function createObj(o) {
        function F() {};
        F.prototype = o;
        return new F();
    }
    createObj() 函数内部,先创建了一个临时性构造函数,然后将传入的对象作为这个构造函数的原型,最后返回了这个临时类型的一个新实例

看个栗子:

function createObj(o) {
    function F() {};
    F.prototype = o;
    return new F();
}

var person = {
    name:'kevin',
    friends:['daisy', 'kelly']
}
var person1 = createObj(person);
var person2 = createObj(person);

person1.name = 'person1';
console.log(person2.name); // kevin

person1.friends.push('taylor');
console.log(person2.friends); // ['daisy', 'kelly', 'taylor']

注意:修改person1.name的值,person2.name的值并未发生改变,并不是因为person1person2有独立的 name 值,而是因为person1.name = 'person1'是给person1添加了 name 值,并非修改了原型上的 name 值。

  • 下面看看原型式的模拟实现:
    function Parent(o) {
        // 创建一个临时性的构造函数
        function F() {}
        // 将传入的对象作为这个构造函数的原型
        F.prototype = o;
        // 返回这个临时类型的一个新实例
        return new F();
    }
    var person = {
        name: "hcy",
        friends: ["et", "siyang"]
    }
    var another = Parent(person);
    console.log(another.name); // hcy
    another.friends.push('hg');
    
    var son = Parent(person);
    console.log(son.friends); // ["et", "siyang", "hg"]
    son.name = 'zbc';
    
    var sister = Parent(person);
    console.log(sister.name); // hcy
  • 缺点:包含引用类型的属性值始终都会共享相应的值,这点跟原型链继承一样
  • 使用场景:不需要单独创建构造函数,但仍然需要在对象间共享信息

寄生式继承

创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象。

举个栗子:

function createObj(o) {
  var clone = Object.create(o);
  clone.sayName = function() {
    console.log('hi');
  }
  return clone;
}

var person = {
  name:'siyang';
  friends:['hg','hcy'];
}
var anotherPerson = createObj(person);
anotherPerson.sayName(); // "hi"

// 将 `createObj` 函数返回的结果赋值给 `clone` ,然后给 `clone` 添加了 sayName 方法
  • 模拟实现:
    function Parent(o) {
      function F() {}
      F.prototype = o;
      return new F();
    }
    function createAnother(original) {
      var clone = Parent(original);
      clone.sayHi = function() {
        alert("Hello World!");
      };
      return clone;
    }
    var person = {
      name:'siyang',
      friends:['hcy']
    }
    var another = createAnother(person);
    another.sayHi(); // Hello World!
  • 缺点:跟借用构造函数模式一样,每次创建对象都会创建一遍方法,函数不能复用使效率低下,与借用构造函数继承类似。
  • 使用场景:主要关注对象,而不在乎类型和构造函数

寄生组合式继承(引用类型最理想的继承范式)

即通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。
基本思路:不通过调用父类构造函数给子类原型赋值,而是取得父类原型的一个副本。
本质上:使用寄生式继承来继承父类原型,然后再将返回的新对象赋值给子类原型。

function inheritPrototype(child, person) {
  var prototype = Object.create(person.prototype);
  prototype.constructor = child;
  child.prototype = prototype;
}

栗子:
先放一个组合继承的代码

function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function() {
  console.log(this.name)
}

function Child(name, age) {
  Parent.call(this, name);
  this.age = age;
}
Child.prototype = new Parent();

var child1 = new Child('kevin', '18');
console.log(child1);

改造目标:不使用 Child.prototype = new Parent() ,而是间接的让 Child.prototype 访问到 Parent.prototype

明白需求之后,开始动手:

function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function() {
  console.log(this.name)
}

function Child(name, age) {
  Parent.call(this, name);
  this.age = age;
}

// 关键的三步
var F = function() {};
F.prototype = Parent.prototype;
Child.prototype = new F();

var child1 = new Child('kevin', '18');
console.log(child1);

于是封装:

function object(o) {
  function F() {};
  F.prototype = o;
  return new F();
}

function prototype(child, parent) {
  var prototype = object(parent.prototye);
  prototype.constructor = child;
  child.prototpe = prototype;
}

// 当我们使用的时候:
prototype(Child, Parent);

优点:只调用了一次 Parent 构造函数,并且因此避免了在 Parent.prototype 上面创建不必要的、多余的属性。同时,原型链还能保持不变;因此,还能够正常使用 instanceofisPrototypeOf。

  • 完整模拟实现:
    function obj(o) {
      function F() {}
      F.prototype = o;
      return new F();
    }
    function inheritPrototype(child, Parent) {
      // 创建父类原型的一个副本
      var _prototype = obj(Parent.prototype);
      // 为创建的副本添加 constructor 属性,弥补因重写原型而失去的默认的 constructor 属性
      _prototype.constructor = child;
      // 将新创建的对象(即副本)赋值给子类原型
      child.prototype = _prototype;
    }
    
    function Parent(name) {
      this.name = name;
      this.colors = ["blue", "red"];
    }
    Parent.prototype.sayName = function() {
      console.log(this.name);
    };
    function child(name, age) {
      Parent.call(this, name);
      this.age = age;
    }
    child.prototype.sayAge = function() {
      console.log(this.age);
    };
    
    inheritPrototype(child, Parent);
    
    var sister = new child('siyang', '20');
    sister.sayAge(); // 20
    sister.sayName(); // siyang
    sister.colors.push('yellow');
    console.log(sister.colors); //  ["blue", "red", "yellow"]

文章作者: hcyety
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 hcyety !
评论
  目录