美文网首页
高程阅读笔记-多重继承

高程阅读笔记-多重继承

作者: _达斯基 | 来源:发表于2018-01-19 00:58 被阅读0次

    JavaScript 不提供多重继承功能,即不允许一个对象同时继承多个对象。但是,可以通过变通方法,实现这个功能。

    function M1() {
      this.hello = 'hello';
    }
    
    function M2() {
      this.world = 'world';
    }
    
    function S() {
      M1.call(this);
      M2.call(this);
    }
    
    // 继承 M1
    S.prototype = Object.create(M1.prototype);
    // 继承链上加入 M2
    Object.assign(S.prototype, M2.prototype);
    
    // 指定构造函数
    S.prototype.constructor = S;
    
    var s = new S();
    s.hello // 'hello:'
    s.world // 'world'
    

    上面代码中,子类S同时继承了父类M1和M2。这种模式又称为 Mixin(混入)。

    in运算符返回一个布尔值,表示一个对象是否具有某个属性。它不区分该属性是对象自身的属性,还是继承的属性。

    'length' in Date // true
    'toString' in Date // true
    

    Object.getOwnPropertyDescriptors(obj)获取属性描述

    相关文章

      网友评论

          本文标题:高程阅读笔记-多重继承

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