js的继承主要分es5和es6两个阶段
- ES5
在es5阶段中,js的继承主要是通过原型链实现的,即js通过构造函数生成新的对象,然后自动将对象关联原型,代码示例
function Animal(feet){
this.feet = feet
}
function Human(name){
Animal.call(this,'2只脚')
this.name = name
}
Animal.prototype.run =function(){
console.log(this.name+'在跑')
}
Human.prototype.__proto__ = Animal.prototype
let emma = new Human('emma')
emma.run()
console.log(emma.__proto__.__proto__ === Animal.prototype)
console.log(emma.__proto__ ===Human.prototype)
由上面的代码可以看出emma对象本身并没有name和feet属性和run方法,但是由于emma的__proto__指向了Human的prototype,并且Human.prototype.__proto__指向了Animal.prototype,,这意味着emma对象不仅有这human的属性还有着animal的属性,所以通过prototype可以实现js继承
- ES6
在es6阶段,可以使用class来声明一个类,并且可以通过extends来实现js继承,代码示例如下:
class Animal{
constructor(feet){
this.feet = feet
}
run(){
console.log('running')
}
}
class Human extends Animal{
constructor(feet,name){
super(feet)
this.name = name
}
}
let emma = new Human('2只脚','emma')
emma.run()
console.log(emma.name+'有'+emma.feet)
console.log(emma.__proto__.__proto__ === Animal.prototype)
console.log(emma.__proto__ ===Human.prototype)