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