继承的本质就是复制,即重写原型对象,代之以一个新类型的实例对象。
- 构造函数里的原型继承
function Message(){
this.name="Cris"
this.gender="man"
}
Message.prototype.getAge=function(){
return this.age=12
}
Message.prototype.gender="women"
let m=new Message()
//下面是输出结果
m; //Message {name: "Cris", gender: "man"}
m.gender; //"man"
m.__proto__.gender; //"woman"
m.getAge()===m.__proto__.getAge(); //true
m.__proto__; //{gender: "women", getAge: ƒ, constructor: ƒ}
m.__proto__.__proto__; //{constructor: ƒ, __defineGetter__: ƒ, __defineSette__: ƒ,hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
m.__proto__.__proto__.__proto__; //null
Object.create()继承原型
let p={a:4}
let obj=Object.create(p)
obj.__proto__===p; //true
- 基于class继承
class S{
constructor(width){
this.width=width
}
getLength(){
return this.width*4
}
}
class W extends S {
constructor(width){
super()
this.width=width
}
getArea(){
return this.width*this.width
}
}
let w=new W(3)
w.getLength() //12
这里W继承了S的原型,super()指向父类的构造函数,里面的this却指向了W,相当于S.prototype.constructor.call(this)
- 总结
始终记住:对象.__proto__ === 构造函数.prototype