我试图将通用功能封装在基类中,并计划从各自的实例调用派生类特定的函数。不知何故,我没有在派生类中获取参数。不确定这里出了什么问题 -
class A {
constructor(callback){
this.callback = callback;
}
write(){
console.log('Writing A');
this.callback(10);
}
}
class B extends A {
constructor(){
super(()=> this.read())
}
read(n){
console.log('Read B: ' + n);
}
}
const b = new B();
b.write();
输出
"Writing A"
"Read B: undefined"
然而,我希望 -
"Writing A"
"Read B: 10"
最佳答案
你有
super(()=> this.read())
回调不带任何参数,也不向 this.read
传递任何内容 - 因此 10
会丢失。
确保回调获取所需参数并传递它。
class A {
constructor(callback){
this.callback = callback;
}
write(){
console.log('Writing A');
this.callback(10);
}
}
class B extends A {
constructor(){
super((n)=> this.read(n))
}
read(n){
console.log('Read B: ' + n);
}
}
const b = new B();
b.write();
更一般地说,随着传播:
class A {
constructor(callback){
this.callback = callback;
}
write(){
console.log('Writing A');
this.callback(10);
}
}
class B extends A {
constructor(){
super((...args)=> this.read(...args))
}
read(n){
console.log('Read B: ' + n);
}
}
const b = new B();
b.write();
关于javascript - ES6 - 使用基类的参数调用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67798789/