重点掌握内容1:原型链的原理
function SuperType(){
this.prototype = true
}
SuperType.prototype.getSuperValue = function(){
return this.propery
}
function SubType(){
this.subproperty = false
}
SubType.prototype = new SuperType() //SubType.prototype.__proto__ === SuperType.prototype
SubType.prototype.getValue = function(){
return this.subproperty
}
var instance = new SubType() //instance.__proto__ == SubType.prototype
console.log(instance.getSuperValue())//instance
在当前属性找不到时,会依次在原型链上找,比如instance.getSuperValue(),引擎在instance的实例中找不到就会去instance.proto上去找,找SubType.prototype,发现还是没有,就会顺着SubType.prototype.proto找到SuperType.prototype,最后在其上找到这个属性方法并返回。
重点掌握内容2:寄生组合继承
function object(o){
function F(){}
F.prototype = o
return new F()
}
function inheritPrototype(subType,superType){
var prototype = object(superType.prototype)//创建对象
prototype.constructor = subType//增强对象
subType.prototype = prototype//指定对象
}
function SuperType(name){
this.name = name
this.colors = ["red","blue","green"]
}
SuperType.prototype.sayName = function(){
console.log(this.name)
}
function Subtype(name,age){
SuperType.call(this,name)//继承到SuperType的函数中属性name以及colors
this.age = age
}
inheritPrototype(SubType,SuperType)//继承到原型中属性sayName:相当于SubType.prototype = new SuperType()继承到SuperType的原型属性
SubType.prototype.sayAge = function(age){
console.log(this.age)
}
SubType.prototype = new SuperType()//
var instance = new SubType("pp",24)