gpt4 book ai didi

javascript - 如何在回调函数中访问 "this"的两个上下文?

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:35 27 4
gpt4 key购买 nike

class MyExampleClass {
constructor(port, service) {
this.port = port;
this.service = service;
this.app = require('express')();
this.http = require('http').createServer(this.app);
}

onListening() {
// Current result: 'listening on port NaN for undefined'
// Desired result: 'listening on port 3000 for test' (I want to CHANGE this behavior)
console.log('listening on port %d for %s', this.port, this.service);

// Current result: 'class: Server'
// Desired result: 'class: Server' (I want to KEEP this behavior)
console.log('class: ' + this.constructor.name);
}

start() {
this.http.listen(this.port, this.onListening);
}
}

const example = new MyExampleClass(3000, 'test');
example.start();

正如onListening方法的注释中所述,我想要访问MyExampleClass实例的上下文以及由createServer创建的Server回调实例。

最佳答案

在构造函数中绑定(bind) this.onListening 以保留 onListening 内的 this 上下文。

您不能让 this 指向 2 个不同的上下文,因此您必须通过 this.http 访问 Server 实例。

class MyExampleClass {
constructor(port, service) {
this.port = port;
this.service = service;
this.app = require('express')();
this.http = require('http').createServer(this.app);

this.onListening = this.onListening.bind(this);
}

onListening() {
console.log('listening on port %d for %s', this.port, this.service);
console.log('class: ' + this.http.constructor.name);
}

start() {
this.http.listen(this.port, this.onListening);
}
}

const example = new MyExampleClass(3000, 'test');
example.start();

关于javascript - 如何在回调函数中访问 "this"的两个上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57668734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com