我很想在 js 中通过重新分配 this 的类来实现多态性。
我有一个类简化为:
class First{
method1 = function(aVar) { this.list.map (e => e === aVar)}
}
另一个类已经从另一个父类继承了:
class Second extends Parent{
constructor(){
this.list = ['some elements'];
this.method1 = First.method1.apply(this, arguments)
}
父级不能从第一个扩展; 当我运行Second时,它会抛出一个错误:apply无法应用于method1,因为它是未定义的, 但是当我创建一个实例时,它失去了第二个范围:
class Second extends Parent{
constructor(){
this.list = ['some elements'];
this.method1 = (new First).method1.apply(this, arguments)
}
我还需要向 First.method1 提供参数
我试过这个answer但这不起作用
最佳答案
事情是 .apply()
触发该函数,而您不想触发该函数,您想创建一个更改为 此
上下文。为此,您需要使用 .bind()
方法来创建函数但不触发它。看一下这段代码:
class First {
method1() {
this.list.map(e => e)
console.log('I got called');
}
method2() {
return this.list;
}
}
class Parent {}
class Second extends Parent {
constructor(){
super();
this.list = ['second class list'];
this.method1 = (new First()).method1.bind(this)
this.theList = (new First()).method2.apply(this);
}
}
const sec = new Second();
sec.method1();
console.log(sec.theList);
因此,Second
类中的 method1
是类 First
中同名方法的副本。它是使用 bind()
创建的,并将 this
更改为 Second
类上下文。
但是,Second
类中的 theList
字段是调用 method2()
的结果具有更改的 this
上下文的 First
类。它不是一个函数,而是函数的结果。
看出区别了吗?
关于javascript - 如何重新定义 'this' 并重用另一个类的方法。多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59095540/