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

标签 javascript node.js

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/

相关文章:

javascript - 使用ajax时Django不渲染数据

javascript - 如何计算用户愤怒的成本

node.js - Nodejs调试生产中的错误

node.js - 为什么当测试失败时 Jenkins 仍然说成功?

node.js - 无法在 shell 脚本中运行 npm

javascript - jQuery - 克隆表单元素并更改标签

javascript - 我试图让每个 "onclick"事件重复该功能

javascript - JavaScript 中的函数式递归方法?不良做法?

node.js - nodejs session 只存储 json?

node.js - 错误 : database names cannot contain the character '.'