JavaScript完成继续

简介

本文不准备深切细节,主假如对《JavaScript高等程序设计中》引见的JS怎样完成继续做一个总结,毕竟好记性不如烂笔头。文末会附带一张神图,搞清楚这张图,原型链也就没有什么题目了。

ES5完成继续的六种体式格局

1. 原型链

基础思想:

应用原型链让一个援用范例继续另一个援用范例的属性和要领。

function SuperType () {
  this.property = true;
}

SuperType.prototype.getSuperValue = function () {
  return this.property;  
};

// 子类 SubType
function SubType () {
  this.subProperty = false;
}

SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function () {
  return this.subProperty;
};

// 实例
var instance = new SubType();
console.log(instance);
console.log(instance.getSuperValue());                            // true
console.log(instance instanceof SubType);                         // true
console.log(instance instanceof SuperType);                       // true
console.log(instance instanceof Object);                          // true
console.log(SubType.prototype.isPrototypeOf(instance));           // true
console.log(SuperType.prototype.isPrototypeOf(instance));         // true
console.log(Object.prototype.isPrototypeOf(instance));            // true

瑕玷:

1. 来自原型对象的援用属性是一切实例同享的。

2. 建立子类实例时,没法向父类组织函数传参。

举例以下:

// 1. 来自原型对象的援用属性是一切实例同享的

// 父类
function SuperType () {
  this.colors = ['red', 'blue', 'green'];
}

// 子类
function SubType () {

}
SubType.prototype = new SuperType();

// 实例
var instance1 = new SubType();
instance1.colors.push('black');
console.log(instance1.colors);        // ['red', 'blue', 'green', 'black']
var instance2 = new SubType();
console.log(instance2.colors);        // ['red', 'blue', 'green', 'black']

// 由于修正colors是修正的SubType.prototype.colors,所以一切的实例都邑更新
// 2. 建立子类实例时,没法向父类组织函数传参

// 挪用父类是在 SubType.prototype = new SuperType()
// 新建子类实例挪用 new SubType()
// 所以没法再new SubType() 的时刻给父类 SuperType() 传参

2. 借用组织函数

基础思想:

在子类组织函数的内部经由历程call()以及apply()挪用父类组织函数。

// 父类 SuperType
function SuperType (name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
  
  this.getName = function () {
      return this.name;
  }
}

// 子类
function SubType (name) {
  // 继续了SuperType,同时还通报了参数
  SuperType.call(this, name);

  // 实例属性
  this.age = 20;
}

// 实例
var instance1 = new SubType('Tom');
instance1.colors.push('black');
console.log(instance1.name);               // "Tom"
console.log(instance1.getName());          // "Tom"
console.log(instance1.age);                // 20
console.log(instance1.colors);             // ['red', 'blue', 'green', 'black']
var instance2 = new SubType('Peter');
console.log(instance2.name);               // "Peter"
console.log(instance2.getName());          // "Peter"
console.log(instance2.age);                // 20
console.log(instance2.colors);             // ['red', 'blue', 'green']

可以看到,借用组织函数完成继续,处理了原型链继续的两个题目,既可以在新建子类实例的时刻给父类组织函数通报参数,也不会形成子类实例同享父类援用变量。

然则你注意到了吗,这里我们把父类要领也写在了SuperType()组织函数内里,可以像前面一样写在SuperType.prototype上吗?

答案是不可以,必需写在SuperType()组织函数内里。由于这里是经由历程挪用SuperType.call(this)来完成继续的,并没有经由历程new天生一个父类实例,所以假如写在prototype上,子类是没法拿到的。

瑕玷:

1. 假如要领都在组织函数中定义,那末就没法复用函数。每次构建实例时都邑在实例中保存要领函数,形成了内存的糟蹋,同时也没法完成同步更新,由于每一个实例都是零丁的要领函数。假如要领写在prototype上,就只会有一份,更新时刻会做到同步更新。

《JavaScript完成继续》

《JavaScript完成继续》

3. 组合继续

基础思想:

将原型链和借用组织函数的手艺组合到一块,从而发挥两者之长的一种继续情势。

运用原型链完成对原型属性和要领的继续,而经由历程借用组织函数来完成对实例属性的继续。

// 父类
function SuperType (name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

SuperType.prototype.sayName = function () {
  console.log(this.name);
}

// 子类
function SubType (name, age) {
  // 继续父类实例属性
  SuperType.call(this, name);
  
  // 子类实例属性
  this.age = age;
}

SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function () {
  console.log(this.age);
};

// 实例
var instance1 = new SubType('Tom', 20);
instance1.colors.push('black');
console.log(instance1.colors);                  // ['red', 'blue', 'green', 'black']
instance1.sayName();                            // "Tom"
instance1.sayAge();                             // 20

var instance2 = new SubType('Peter', 30);
console.log(instance2.colors);                  // ['red', 'blue', 'green']
instance2.sayName();                            // "Peter"
instance2.sayAge();                             // 30

瑕玷:

1. 挪用了两次父类组织函数,一次经由历程SuperType.call(this)挪用,一次经由历程new SuperType()挪用。

4. 原型式继续

基础思想:

不运用严厉意义上的组织函数,借助原型可以基于已有的对象建立新的对象,同时还没必要因而建立自定义范例。

// 在object函数内部,先建立了一个暂时的组织函数,然后将传入的对象作为这个组织函数的原型,末了返回这个暂时范例的一个新实例。
// 从本质上讲,object()对传入个中的对象执行了一次浅复制。

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


var person = {
  name: 'Tom',
  friends: ['Shelby', 'Court', 'Van']
};

var anotherPerson = object(person);
anotherPerson.name = 'Greg';
anotherPerson.friends.push('Rob');

var yetAnotherPerson = object(person);
yetAnotherPerson.name = 'Linda';
yetAnotherPerson.friends.push('Barbie');

console.log(anotherPerson.friends);               // ['Shelby', 'Court', 'Van', 'Rob', 'Barbie']
console.log(yetAnotherPerson.friends);            // ['Shelby', 'Court', 'Van', 'Rob', 'Barbie']
console.log(person.friends);                      // ['Shelby', 'Court', 'Van', 'Rob', 'Barbie']

ECMAScript5中新增了一个要领Object.create(prototype, descripter)吸收两个参数:

  • prototype(必选),用作新对象的原型对象
  • descripter(可选),为新对象定义分外属性的对象

在传入一个参数的情况下,Object.create()与前面写的object()要领的行动雷同。

var person = {
  name: 'Tom',
  friends: ['Shelby', 'Court', 'Van']
};

var anotherPerson = Object.create(person);
anotherPerson.name = 'Greg';
anotherPerson.friends.push('Rob');

var yetAnotherPerson = Object.create(person, {
    name: {
        value: 'Linda',
        enumerable: true
    }
});
yetAnotherPerson.friends.push('Barbie');

console.log(anotherPerson.friends);               // ['Shelby', 'Court', 'Van', 'Rob', 'Barbie']
console.log(yetAnotherPerson.friends);            // ['Shelby', 'Court', 'Van', 'Rob', 'Barbie']
console.log(person.friends);                      // ['Shelby', 'Court', 'Van', 'Rob', 'Barbie']

瑕玷:

1. 和原型链继续一样,一切子类实例同享父类的援用范例。

5. 寄生式继续

基础原理:

寄生式继续是与原型式继续严密相干的一种思绪,建立一个仅用于封装继续历程的函数,该函数内部以某种情势来做加强对象,末了返回对象。

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

function createAnother (o) {
  var clone = object(o);
  clone.sayHi = function () {
    console.log('Hi');
  }
  return clone;
}

var person = {
  name: 'Tom',
  friends: ['Shelby', 'Court', 'Van'] 
};

var anotherPerson = createAnother(person);
anotherPerson.sayHi();                              // "Hi"
anotherPerson.friends.push('Rob');
console.log(anotherPerson.friends);              // ['Shelby', 'Court', 'Van', 'Rob']
var yerAnotherPerson = createAnother(person);
console.log(yerAnotherPerson.friends);              // ['Shelby', 'Court', 'Van', 'Rob']

瑕玷:

1. 和原型链式继续一样,一切子类实例同享父类援用范例。

2. 和借用组织函数继续一样,每次建立对象都邑建立一次要领。

6. 寄生组合式继续

基础思想:

将寄生式继续和组合继续相结合,处理了组合式继续中会挪用两次父类组织函数的瑕玷。

组合继续是JavaScript最经常使用的继续情势,它最大的题目就是不管在什么情况下,都邑挪用两次父类组织函数:一次是在建立子类原型的时刻,另一次是在子类组织函数内部。

// 组合继续
function SuperType(name) {
  this.name = name;
  this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function () {
  alert(this.name);
};
function SubType(name, age) {
  SuperType.call(this, name); //第二次挪用 SuperType()
  this.age = age;
}
SubType.prototype = new SuperType(); //第一次挪用 SuperType()
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function () {
  alert(this.age);
};

组合继续在第一次挪用SuperType组织函数时,SubType.prototype会获得两个属性:name和colors;它们都是 SuperType 的实例属性,只不过如今位于 SubType的原型中。当挪用SubType组织函数时,又会挪用一次SuperType组织函数,这一次又在新对象上建立了实例属性name和colors。因而,这两个属性就屏障了原型中的两个同名属性。

所谓寄生组合式继续,即经由历程借用组织函数来继续属性,经由历程原型链的混成情势来继续要领。

其背地的基础思绪是:没必要为了指定子范例的原型而挪用父类的组织函数,我们须要的不过就是父类原型的一个副本罢了。本质上,就是运用寄生式继续来继续父类的prototype,然后再将效果指定给子类的prototype。

寄生组合式继续的基础模子以下:

function inheritPrototype(SubType, SuperType) {
    var prototype = object(SuperType.prototype);        // 建立对象
    prototype.constructor = SubType;    // 加强对象
    SubType.prototype = prototype;      // 指定对象
    
}

完成一个完全的寄生组合式继续:

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

function inheritPrototype(SubType, SuperType) {
  var prototype = object(SuperType.prototype);        // 建立对象
  prototype.constructor = SubType;    // 加强对象
  SubType.prototype = prototype;      // 指定对象 
}

// 父类
function SuperType(name) {
  this.name = name;
  this.colors = ["red", "blue", "green"];
}

SuperType.prototype.sayName = function () {
  console.log(this.name);
};

// 子类
function SubType(name, age) {
  // 继续父类实例属性
  SuperType.call(this, name);

  // 子类实例属性
  this.age = age;
}

// 继续父类要领
inheritPrototype(SubType, SuperType);

// 子类要领
SubType.prototype.sayAge = function () {
  console.log(this.age);
};

// 实例
var instance1 = new SubType('Tom', 20);
instance1.colors.push('black');
instance1.sayAge();                                   // 20
instance1.sayName();                                  // "Tom"
console.log(instance1.colors);                        // ["red", "blue", "green", "black"]

var instance2 = new SubType('Peter', 30);
instance2.sayAge();                                   // 30
instance2.sayName();                                  // "Peter"
console.log(instance2.colors);                        // ["red", "blue", "green"]

寄生组合式继续的高效率体如今它只挪用了一次SuperType组织函数,而且因而避免了再SubType.prototype上面建立没必要要的、过剩的属性。与此同时,原型链还能坚持稳定。因而,还可以一般运用instanceof和isPrototypeOf()。

开发人员普遍认为寄生组合式继续是援用范例最理想的继续体式格局。

ES6完成继续

// 父类
class SuperType {
  constructor(name) {
    this.name = name;
    this.colors = ["red", "blue", "green"];
  }

  sayName() {
    console.log(this.name);
  };
}

// 子类
class SubType extends SuperType {
  constructor(name, age) {
    // 继续父类实例属性和prototype上的要领
    super(name);
    
    // 子类实例属性
    this.age = age;
  }

  // 子类要领
  sayAge() {
    console.log(this.age);
  }
}

// 实例
var instance1 = new SubType('Tom', 20);
instance1.colors.push('black');
instance1.sayAge();                                   // 20
instance1.sayName();                                  // "Tom"
console.log(instance1.colors);                        // ["red", "blue", "green", "black"]

var instance2 = new SubType('Peter', 30);
instance2.sayAge();                                   // 30
instance2.sayName();                                  // "Peter"
console.log(instance2.colors);                        // ["red", "blue", "green"]

用ES6的语法来完成继续异常的简朴,下面是把这段代码放到Babel里转码的效果图片:

《JavaScript完成继续》

可以看到,底层实在也是用寄生组合式继续来完成的。

总结

ES5完成继续有6种体式格局:

  1. 原型链继续
  2. 借用组织函数继续
  3. 组合继续
  4. 原型式继续
  5. 寄生式继续
  6. 寄生组合式继续

寄生组合式继续是人人公认的最好的完成援用范例继续的要领。

ES6新增class和extends语法,用来定义类和完成继续,底层也是采用了寄生组合式继续。

附图:

《JavaScript完成继续》

迎接关注我的民众号

《JavaScript完成继续》

    原文作者:liuxuan
    原文地址: https://segmentfault.com/a/1190000016184431
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞