1. 原型链继承
function Parent() {this.name = ['kevin', 'klay'];}function Child() {}// Child的原型重新赋值为Parent的实例Child.prototype = new Parent();var child1 = new Child();// 此时的name为原型链上Parent.prototype的属性child1.name.push('stephen'); // ['kevin', 'klay', 'stephen']console.log(child1.name);var child2 = new Child();console.log(child2.name); // ['kevin', 'klay', 'stephen']
原理:在读取实例上的属性时,首先在实例上搜索该属性,如果没找到,则继承搜索实例的原型,在通过原型链实现继承之后,搜索就可以继承向上,搜索原型的原型。
缺点:1. 引用类型的属性被所有实例共享;
2. 在创建Child实例时,不能向Parent传参
2. 借用构造函数(经典继承)
function Parent() {this.name = ['kevin', 'klay'];}function Child() {// 继承Parent的属性Parent.call(this);}var child1 = new Child();// 此时的name为 Child1 中的属性child1.name.push('stephen'); // ['kevin', 'klay', 'stephen']console.log(child1.name);var child2 = new Child();console.log(child2.name); // ['kevin', 'klay']
原理:在子类构造构造函数中调用父类构造函数;
优点:避免了引用类型的属性被所有实例共享,同时,可以在Child中给Parent传参。
缺点:1. 方法都在构造函数中定义,每次创建实例都会创建一遍方法;
2. 子类不能访问父类原型上定义的方法
3. 组合继承
function Parent(name) {this.name = name;this.colors = ['red', 'blue', 'green'];}Parent.prototype.getName = function() {console.log(`hello, ${this.name}`)}function Child(name, age) {// 继承属性Parent.call(this, name); // 第二次调用 Parentthis.age = age;}// 继承方法Child.prototype = new Parent() // 第一次调用 Parentvar child1 = new Child('btqf', 18);child1.colors.push('yellow');console.log(child1.name); // btqfconsole.log(child1.colors); // ['red', 'blue', 'green', 'yellow']var child2 = new Child('kevin', 20);console.log(child2.name); // kevinconsole.log(child2.colors); // ['red', 'blue', 'green']console.log(child2.getName()) // 'hello, kevin'
**原理: **使用原型链继承原型上的属性和方法,通过盗用构造函数继承实例属性<br />**优点:**可以共享相同的方法,然后不同的实例由自己的属性,是JS中最常用的继承模式。
4. 原型式继承
function createObj(o) {function F(){}F.prototype = o;return new F();}let person = {name: 'btqf',friends: ['kevin', 'stephen']}let person1 = createObj(person);let person2 = createObj(person);person1.name = 'person1';console.log(person2.name); // btqfperson1.friends.push('klay');console.log(person2.friends) // ['kevin', 'stephen', 'klay']
原理: ES5 Object.create的模拟实现,将传入的对象作为创建的对象的原型
缺点:包含应用类型的属性值始终都会共享相应的值
5. 寄生式继承
function createObj (o) {var clone = Object.create(o); // 创建对象clone.sayName = function () { // 增强对象console.log('hi');}return clone; // 返回对象}
**原理:**创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象。<br />**缺点:**与借用构造函数一致,每次创建对象都会创建一遍方法。
6. 寄生组合式继承
// 组合式继承包含着重复调用,为了解决该问题,引入了寄生组合式继承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;}function object(o) {function F() {}F.prototype = o;return new F();}function prototype(child, parent) {var prototype = object(parent.prototype);prototype.constructor = child;child.prototype = prototype;}// 当我们使用的时候:prototype(Child, Parent);
它只调用了一次 Parent 构造函数,并且因此避免了在 Parent.prototype 上面创建不必要的、多余的属性。与此同时,原型链还能保持不变;因此,还能够正常使用 instanceof 和 isPrototypeOf。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式。
