我尝试在函数及其超级函数执行完毕后执行回调。
重要的是:
给出以下示例:
class Car {
constructor(props) {
this.props = props;
}
brake() {
this.activateBrakes();
}
activateBrakes() {
console.log('1');
}
}
class Prius extends Car {
brake() {
super.brake();
this.activateRegenerativeBrakingSystem();
}
activateRegenerativeBrakingSystem() {
console.log('2');
}
}
var onBrake = () => console.log('after');
var car = new Car({onBrake});
car.brake();
var prius = new Prius({onBrake});
prius.brake();

https://jsfiddle.net/pL4jzcwv/20/
如何打印控制台:
"1"
"after"
"1"
"2"
"after"
我没有打电话给布拉克,因为据我所知,没有任何地方可以按原样放置控制台记录所描述的内容。
答案 0 :(得分:0)
我可以想到两种方法:
1。将制动的实施与方法brake
分开,让Car
的{{1}}调用回调。
brake
(而class Car {
// ...
brake() {
this.brakeImplementation(); // <==
this.props.onBrake(); // <==
}
brakeImplementation() { // <==
this.activateBrakes(); // <==
} // <==
// ...
}
会覆盖Prius
,而非brakeImplementation
。)
直播示例:
brake
2。有一个方法,比如class Car {
constructor(props) {
this.props = props;
}
brake() {
this.brakeImplementation();
this.props.onBrake();
}
brakeImplementation() {
this.activateBrakes();
}
activateBrakes() {
console.log('1');
}
}
class Prius extends Car {
brakeImplementation() {
super.brakeImplementation();
this.activateRegenerativeBrakingSystem();
}
activateRegenerativeBrakingSystem() {
console.log('2');
}
}
var onBrake = () => console.log('after');
var car = new Car({onBrake});
car.brake();
var prius = new Prius({onBrake});
prius.brake();
,它接受一个构造函数,只有在传入的构造函数是实例的构造函数时才调用回调:
doneBraking
然后在每个班级的doneBraking(ctor) {
if (ctor === this.constructor) {
this.props.onBrake();
}
}
末尾拨打电话:
brake
有点难看,但...... :-)直播示例:
class Car {
// ...
brake() {
this.activateBrakes();
this.doneBraking(Car); // <==
}
// ...
}
class Prius extends Car {
// ...
brake() {
super.brake();
this.activateRegenerativeBrakingSystem();
this.doneBraking(Prius); // <==
}
// ...
}
答案 1 :(得分:0)
可能是我误解了你,但是你提到了事件循环,我想知道将你的回调onBrake
推送到事件循环作为下一个 io 任务(process.nextTick),然后它可以用async
函数实现这个想法。
以下示例仅适用于 node.js 。
class Emitter {
constructor(props) {
this.events = []
}
add(event) {
if (!this.events.includes(event.name)) {
this.events.push(event.name)
process.nextTick(event)
}
}
remove(event) {
this.events = this.events.filter(name => name !== event.name)
}
}
class Car {
constructor(props) {
this.props = props
this.event = new Emitter()
}
async brake() {
this.activateBrakes()
this.onBrake()
}
activateBrakes() {
console.log(1)
}
async onBrake () {
this.event.add(this.props.onBrake)
}
}
class Prius extends Car {
async brake() {
super.brake()
this.activateRegenerAtiveBrakingSystem()
this.onBrake()
}
activateRegenerAtiveBrakingSystem() {
console.log(2)
}
drive() {
this.event.add(() => console.log(` drive`))
}
}
const onBrake = () => console.log(`✋ stop`)
async function main() {
const car = new Car({onBrake})
await car.brake()
const prius = new Prius({onBrake})
prius.brake()
prius.drive()
}
main()
<强>输出强>