为了账号安全,请及时绑定邮箱和手机立即绑定

es6 多重继承

es6 多重继承

HUX布斯 2019-03-15 15:15:22
我在阮一峰的es6教程中看到使用mixin模式,实现多重继承。mixins是一个被继承类数组。我不太明白为什么 copyProperties(Mix, mixin); 可以拷贝实例属性。mixin打印mixin的key只有length,prototype和name取不到其创建的属性例如 class a{constructor(){this.age=16}console.log(Reflect.ownKeys(a))//length,prototype,name,不会取到age原文地址http://es6.ruanyifeng.com/#do...
查看完整描述

2 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

class A{

        constructor(){

            thia.age=1;

        }

        static get A(){

            return 1;

        }

    }

    A.s=1;

    console.log(Reflect.ownKeys(A));

Reflect.ownKeys从方法上就知道是取对象本身上的可枚举属性 而函数其实是一个有[[call]]的对象 class是function的语法糖 所以这时候取的就是class本身的属性 而不是实力的属性 基本可以理解为静态属性/方法


查看完整回答
反对 回复 2019-03-19
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

事实就是不能实现的,如果是下面这两种情况,都是绑定在构造函数中的,阮一峰那种方法很明显不能用。


class A {

    age = 20;

    getAge = () => {

        return this.age;

    }

}

这种写法其实等价于:


function A() {

    this.age = 20;

    this.getAge = function() {

        return this.age;

    }

}

这种情况下是无法拿到age和getAge的,我最近也在想这个多重继承的问题,我能想到的是手动实现extends,实现Child -> Parent1 -> Parent2 -> Parent3这样的原型链,我参考了babel后的extends的实现。


class Child {

    name = "111"

    constructor() {

        Child.__proto__.apply(this, arguments);

    }

}

class Parent1 {

    name = "222"

    constructor() {

        Parent1.__proto__.apply(this, arguments);

    }

}

class Parent2 {

    name = "333"

    constructor() {

        Parent2.__proto__.apply(this, arguments);

    }

}

Child.__proto__ = Parent1;

Parent1.__proto__ = Parent2;

Child.prototype.__proto__ = Parent1.prototype;

Parent1.prototype__proto__ = Parent2.prototype;

这里可以实现一个Mixin的方法,通过reduce实现上面繁琐的步骤。

但是有两个问题,一个是要在类的constructor里面使用apply,另一个是父类的属性会覆盖子类的属性,比如上面的name属性,除非把name手动的在constructor里面写到apply后面,这个其实就是《js高级程序设计》里面组合继承的借用构造函数。

如果全部使用ES5的写法,这个多重继承是没啥问题的,但是用ES6这样写的话会很不优雅,也不完美,我目前还没想到好的解决方案。


查看完整回答
反对 回复 2019-03-19
  • 2 回答
  • 0 关注
  • 695 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信