JavaScript实现继承
JavaScript原型和原型链
每个函数都有prototype属性指向它们的原型对象(存在一些特殊情况,例如Function的原型对象是一个函数但是没有prototype属性)
每个对象都有__proto__属性指向它们构造函数的原型对象(存在一些特殊情况,例如Object.create(null)创建的对象就没有__proto__属性)
原型链就是通过__proto__属性将对象和原型连接起来,因为原型也是对象,也有自身的原型,这样层层连接就组成了原型链
原型链的终点就是Object.prototype,Object.prototype.__proto__ === null
JavaScript继承
js是通过原型链实现继承的
一个对象在查找某个属性时,首先会在自身上查找,若没有就会沿着原型链向上查找,直到找到或者到达原型链的终点为止
组合继承
function Parent (name) { this.name = name } Parent.prototype.getName = function () { return this.name } function Child (name, age) { Parent.call(this, name) this.age = age } Child.prototype = new Parent() Child.prototype.constructor = Child Child.prototype.getAge = function () { return this.age } var child = new Child('aa', 18) console.log(child.getName()) // aa console.log(child.getAge()) // 18
寄生组合继承
function Parent (name) { this.name = name } Parent.prototype.getName = function () { return this.name } function Child (name, age) { Parent.call(this, name) this.age = age } Child.prototype = Object.create(Parent.prototype) Child.prototype.constructor = Child Child.prototype.getAge = function () { return this.age } var child = new Child('aa', 18) console.log(child.getName()) // aa console.log(child.getAge()) // 18
class继承
class Parent {
constructor (name) {
this.name = name
}
getName () {
return this.name
}
} class Child extends Parent {
constructor (name, age) {
super(name)
this.age = age
} getAge () {
return this.age
} }
var child = new Child('aa', 18) console.log(child.getName()) // aa console.log(child.getAge()) // 18