2017-08-16 48 views
0

我有三个类,其中两个扩展了第三个类。是否有可能以某种方式(不同于手动)将扩展类的名称分配给超级构造函数?在构造函数中保存扩展类的'方法'名称

class Master { 

    constructor(options) { 
     this.methods = Object.getOwnPropertyNames(Master.prototype); 
    } 

    getMethods() { 
     return Object.getOwnPropertyNames(Master.prototype); 
    } 

} 

class SlaveOne extends Master { 
    constructor(options) { 
     super(options); 
    } 
    methodOne() {} 
    methodTwo() {} 
} 

class SlaveTwo extends Master { 
    constructor(options) { 
     super(options); 
    } 
    methodThree() {} 
    methodFour() {} 
} 

所以,我要的是有两种方法,或在大师班this.methods分配,这将:

  • 回报['constructor', 'methodOne', 'methodTwo']叫上SlaveOne实例时;
  • 返回['constructor', 'methodThree', 'methodFour']当在SlaveTwo的实例上调用时;或者叫做对SlaveOneSlaveTwoMaster实例时

我当前的代码将返回相同['constructor', 'getMethods']。有任何想法吗?

+0

刚刚获得this'对象的'所有方法,它继承的原型。 – Bergi

回答

1

像这样的东西应该做的伎俩

class Master { 
 

 
    getMethods() { 
 
     return Object.getOwnPropertyNames(this.constructor.prototype); 
 
    } 
 

 
} 
 

 
class SlaveOne extends Master { 
 
    constructor(options) { 
 
     super(options); 
 
    } 
 
    methodOne() {} 
 
    methodTwo() {} 
 
} 
 

 
class SlaveTwo extends Master { 
 
    constructor(options) { 
 
     super(options); 
 
    } 
 
    methodThree() {} 
 
    methodFour() {} 
 
} 
 

 
console.log(new SlaveOne().getMethods(), new SlaveTwo().getMethods())

+0

非常感谢,正是我需要的。 – wscourge

+1

更好地使用'Object.getPrototypeOf(this)'而不是'this.constructor.prototype' – Bergi

+0

@Bergi只是想知道为什么它在给定的情况下更好。这里可能会出现'this.constructor.prototype'错误? –