JS里的继承

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 = '人类'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容