关于javascript:JS深挖实现继承方式汇总

6次阅读

共计 1485 个字符,预计需要花费 4 分钟才能阅读完成。

本文次要介绍实现继承的六种形式及各自的优缺点,顺次是

 原型链继承
构造函数继承
组合继承
原型式继承
寄生式继承
寄生式组合继承 

1、原型链继承

 长处:能够复用父类的办法
毛病:1)援用类型会被子类扭转;2)无奈传递参数 
// 代码 1
function Fa() {
  this.name = 'fa'
  this.info = {age: 11}
}

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

function Son() {}

Son.prototype = new Fa(); // 外围
Son.prototype.constructor = Son; // 补上

2、构造函数继承

 长处:1) 能够传递参数;2) 援用属性不会被共享;毛病:子类不能拜访父类上的 prototype;
function Fa() {
  this.name = 'fa'
  this.info = {age: 11}
}

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

function Son() {Fa.call(this)        // 外围
}

3、组合继承

长处:联合下面两个长处

function Fa() {
  this.name = 'fa'
  this.info = {age: 11}
}

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

function Son() {Fa.call(this)
}

Son.prototype = new Fa();
Son.prototype.constructor = Son;

4、原型式继承

 长处:能够复用父类的办法
毛病:1)援用类型会被子类扭转;2)子类申明无奈传递参数;
let Fa = {
  name: 'Fa',
  groups: [1, 2, 3],
  sayName: function () {console.log(this.name);
  }
}

let son = Object.create(Fa);  // 外围

5、寄生式继承

在 4)的根底上,减少了子类的特有办法,优缺点同上;

let Fa = {
  name: 'Fa',
  groups: [1, 2, 3],
  sayName: function () {console.log(this.name);
  }
}

function myCreate(obj) {let clone = Object.create(obj);
  // 自定义新办法
  clone.getName = function () {console.log(this.name + 'haha');
  }
  return clone;
}

6、寄生式组合继承

就是联合了下面所有的长处,就是 class 的外部实现

// 外围函数
function inheritPrototype(child, parent) {let prototype = Object.create(parent.prototype); // 创建对象
  prototype.constructor = child; // 加强对象
  Child.prototype = prototype; // 赋值对象
}

// 定义父类
function Parent(name) {
  this.name = name;
  this.friends = ["rose", "lily", "tom"]
}

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

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

inheritPrototype(Child, Parent);
正文完
 0