重点掌握内容1:原型链的原理

  1. function SuperType(){
  2. this.prototype = true
  3. }
  4. SuperType.prototype.getSuperValue = function(){
  5. return this.propery
  6. }
  7. function SubType(){
  8. this.subproperty = false
  9. }
  10. SubType.prototype = new SuperType() //SubType.prototype.__proto__ === SuperType.prototype
  11. SubType.prototype.getValue = function(){
  12. return this.subproperty
  13. }
  14. var instance = new SubType() //instance.__proto__ == SubType.prototype
  15. console.log(instance.getSuperValue())//instance

在当前属性找不到时,会依次在原型链上找,比如instance.getSuperValue(),引擎在instance的实例中找不到就会去instance.proto上去找,找SubType.prototype,发现还是没有,就会顺着SubType.prototype.proto找到SuperType.prototype,最后在其上找到这个属性方法并返回。
1.png

重点掌握内容2:寄生组合继承

  1. function object(o){
  2. function F(){}
  3. F.prototype = o
  4. return new F()
  5. }
  6. function inheritPrototype(subType,superType){
  7. var prototype = object(superType.prototype)//创建对象
  8. prototype.constructor = subType//增强对象
  9. subType.prototype = prototype//指定对象
  10. }
  11. function SuperType(name){
  12. this.name = name
  13. this.colors = ["red","blue","green"]
  14. }
  15. SuperType.prototype.sayName = function(){
  16. console.log(this.name)
  17. }
  18. function Subtype(name,age){
  19. SuperType.call(this,name)//继承到SuperType的函数中属性name以及colors
  20. this.age = age
  21. }
  22. inheritPrototype(SubType,SuperType)//继承到原型中属性sayName:相当于SubType.prototype = new SuperType()继承到SuperType的原型属性
  23. SubType.prototype.sayAge = function(age){
  24. console.log(this.age)
  25. }
  26. SubType.prototype = new SuperType()//
  27. var instance = new SubType("pp",24)