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/