Javascript 继承的六种方法

1.原型链

  • 利用原型让一个引用类继承另一个引用类型的属性和方法
 1 function superType() {
 2     this.property = true;
 3 }
 4 
 5 superType.prototype.getSuperValue = function () {
 6     return this.property;
 7 }
 8 
 9 function subType() {
10     this.subProperty = false;
11 }
12 
13 subType.prototype = new superType();
14 subType.prototype.getSubValue = function () {
15     return this.subProperty;
16 }
17 
18 var instance = new subType();
19 console.log(instance.getSuperValue());

2.借用构造函数

  • 在子类的构造函数的内部调用超类的构造函数,使用call()或apply()函数。
 1 function superType(name) {
 2     this.name = name;
 3 }
 4 
 5 function subType() {
 6     // 继承了超类,同时还传递了参数
 7     superType.call(this, 'Nick');
 8     this.age = 29;
 9 }
10 
11 var instance = new subType();
12 console.log(instance.name);
  • 方法都是在构造函数中创建的,无法进行复用。

3.组合继承

  • 结合原型链继承和借用构造函数继承的优点,可以让两个实例有不同的属性,又可以拥有共同的方法
 1 function superType(name) {
 2     this.name = name;
 3     this.color = ["red", "blue"];
 4 }
 5 
 6 superType.prototype.sayName = function () {
 7     console.lgo(this.name);
 8 }
 9 
10 function subType(name, age) {
11     superType.call(this, name);
12     this.age = age;
13 }
14 // 继承
15 subType.prototype = new superType();
16 subType.prototype.sayAge = function () {
17     console.log(this.age);
18 }
19 
20 var instance = new subType('Nick', 29);
21 instance.sayAge();

4.原型式继承

 1 function object(o) {
 2     function F() { };
 3     F.prototype = o;
 4     return new F();
 5 }
 6 // 这个方法和 Object.create()函数类似,不过后者只兼容主流浏览器
 7 var person = {
 8     name: "Nick",
 9     age: 29
10 }
11 
12 var another = Object.create(person);
13 console.log(another.name);

5.寄生

  •  类似于寄生构造模式和工厂模式,即创建一个函数将这个过程封装。
 1 function another(original) {
 2     var clone = Object.create(original);
 3     clone.sayHi = function () {
 4         console.log('Hi');
 5     }
 6     return clone;
 7 }
 8 
 9 var person = {
10     name: 'Nick',
11     age: 29
12 }
13 
14 var ins = another(person);
15 ins.sayHi();

6.寄生组合式继承

  • 只需要调用一次超类构造函数,效率高,并且避免了在prototype和子类上创建不必要的、多余的属性。与此同时,原型链不会变,还可以正常使用instance和isPrototypeOf()。
 1 function inheritPrototype(subType, superType) {
 2     var prototype = Object.create(superType.prototype);    // 创建对象
 3     prototype.costructor = subType; //增强对象
 4     subType.prototype = prototype; // 指定对象
 5 }
 6 
 7 function superType(name) {
 8     this.name = name;
 9     this.color = ["red", "blue"];
10 }
11 
12 superType.prototype.sayName = function () {
13     console.log(this.name);
14 }
15 
16 function subType(name, age) {
17     superType.call(this, name);
18     this.age = age;
19 }
20 
21 inheritPrototype(subType, superType);
22 
23 subType.prototype.sayAge = function () {
24     console.log(this.age);
25 }
26 
27 // 实例化
28 var instance = new subType("Boer", 40);
29 instance.sayName();
原文地址:https://www.cnblogs.com/gemicat/p/4817411.html