美文网首页
JS里的继承

JS里的继承

作者: 彭奕泽 | 来源:发表于2018-06-04 22:21 被阅读0次

    1. 继承

    1. 简介
      一层原型链搜索不叫继承,两层原型链的搜索才叫继承

      let a = new Array();
      a.__proto__ === Array.prototype
      a.push()  
      //这个方法是Array.prototype的,不是继承
      
      a.__proto__.__proto__ === Object.prototype
      a.valueOf()  
      //这个方法是Object.prototype里的,是继承
      

      a.valueOf()这个方法就叫继承的

    2. 实现

    • ES5的继承
      function Human(name){
        this.name = name;
      }
      Human.prototype.run = function(){
        console.log("我叫" + this.name + "我在跑步")
        return
      }
      
      function Man(name){
        Human.call(this,name);  
        //引用Humnan的自身的属性属性
        this.gender = '男'
      }
      Man.prototype.fight = function(){
        console.log('打架')
      }
      Man.prototype.__proto__ = Human.prototype
      //将Man的原型的原型指向Human.prototype
      let pyz = new Man('pyz')
      
      这样pyz.run就是继承属性,因为经过了两层原型链的搜索。
      兼容IE,Man.prototype.__proto__ = Human.prototype这句IE不支持,可以写成下面这样
      let f = function(){}
      f.prototype = Human.prototype
      Man.prototype = new f();
      
    • ES6
      class Human{
        constructor(name){
          this.name = name
        }
        run(){
          console.log('我叫' + this.name + '我在跑步')  
          return
        }
      }
      
      class Man extends Human{  //继承Human的原型链
        constructor(name){
          super(name)  //用它继承的类里的name
          this.gender = '男'
        }
        fight(){}
      }
      
    1. ES5、ES6的优劣
      用ES6在原型声明非函数的方法很奇怪。。。
      ES5可以Human.prototype.race = '人类'

    相关文章

      网友评论

          本文标题:JS里的继承

          本文链接:https://www.haomeiwen.com/subject/ahrysftx.html