参考:developer.mozilla.org/zh-CN/docs/…
何时在 JavaScript 中使用继承?
如果您开始创建一系列拥有相似特性的对象时,那么创建一个包含所有共有功能的通用对象,然后在更特殊的对象类型中继承这些特性,将会变得更加方便有用。
ES5中的继承写法:
function Person(props){
this.name=props.name;
this.age=props.age;
}
Person.prototype.sayHello=function (){
console.log('hello i am '+this.name+' age '+this.age)
}
function Man(props){
Person.call(this,props)
this.gender=props.gender;
this.tellGender=function (){
console.log('hello i am '+this.gender)
}
}
//第一种写法
//直接将Man的prototype指向了Person.prototype生成的对象
Man.prototype=Object.create(Person.prototype)
//此时constructor还是指向Person 需要将其改回来
Man.prototype.constructor=Man;
//第二种写法
//设置一个中间函数f f函数的prototype指向Person.prototype
function f(){}
f.prototype=Person.prototype;
//将Man.prototype作为f函数的实例
Man.prototype=new f()
Man.prototype.constructor=Man;
//继续在Man原型(就是new F()对象)上定义方法:
Man.prototype.tellGender=function (){
console.log('hello i am '+this.gender)
}
let Jack=new Man({name:'honey',age:'45',gender:'man'})
Jack.tellGender()//hello i am man
Jack.sayHello() //hello i am honey age 45
此种继承方法关键一点就是改变继承对象的prototype的指向,使其间接指向被继承对象的protoType,从而拿到继承对象上的属性及方法。
ES6继承方法:
class Person{
constructor(props){
this.name=props.name;
this.age=props.age;
}
sayHello (){
console.log('hello i am '+this.name+' age '+this.age)
}
}
class Man extends Person{
constructor(props){
super(props);//注意:必须在super中声明才能调用父类方法!
this.gender=props.gender;
}
tellGender (){
console.log('hello i am '+this.gender)
}
}