- 原型链继承
让一个构造函数的原型(prototype)是另一个构造函数的实例。
优点:写法方便简洁,容易理解。
缺点:对象实例共享所有继承的属性和方法,不能传递参数。
function Person(age) {
this.name = '张三'
this.age = age
}
Person.prototype.say = function() {
console.log('hello')
console.log(this.age); // undefined
}
function Child(age) {
}
Child.prototype = new Person(18)
let c = new Child(18)
console.log(c) // 张三
c.say() // hello
- 构造函数继承
在子类型构造函数的内部调用父类型构造函数;使用 apply() 或 call() 方法将父对象的构造函数绑定在子对象上。
优点:解决原型链继承无法传参问题和父类的原型共享的问题。
缺点:方法需要在构造函数中定义,无法实现函数复用。父函数原型上定义的函数,子函数不可用。
function Person(age) {
this.name = '张三'
this.age = age
}
Person.prototype.say = function () {
console.log('hello')
console.log(this.age);
}
function Child(age) {
Person.call(this, age)
}
let c = new Child(18)
console.log(c); // Child {name: '张三', age: 18}
c.say() // TypeError: c.say is not a function
- 组合式继承
将 原型链继承 和 构造函数继承 的组合到一块。
优点: 解决了原型链继承和借用构造函数继承造成的影响。
缺点: 无论在什么情况下,都会调用两次父构造函数:一次是在创建子类型原型的时候,另一次是在子类型构造函数内部。
function Person(age) {
this.name = '张三'
this.age = age
}
Person.prototype.say = function () {
console.log('hello')
console.log(this.age); // 18
}
function Child(age) {
Person.call(this, age)
}
Child.prototype = new Person()
let c = new Child(18)
console.log(c.name) // 张三
c.say() // hello
- ES6 中的 class 类继承 extends
优点:语法简单易懂,操作更方便。
缺点:有兼容性问题,并不是所有的浏览器都支持 class 关键字
class Person {
constructor(name) {
this.name = '张三'
}
say() {
console.log('hello');
}
}
class Child extends Person {
constructor(name) {
super(name)
}
// say() {
// super.say()
// }
}
let c = new Child()
console.log(c.name); // 张三
c.say() // hello