2 回答
![?](http://img1.sycdn.imooc.com/545861f00001be3402200220-100-100.jpg)
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本身的属性 而不是实力的属性 基本可以理解为静态属性/方法
![?](http://img1.sycdn.imooc.com/533e4d660001312002000200-100-100.jpg)
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这样写的话会很不优雅,也不完美,我目前还没想到好的解决方案。
添加回答
举报