javascript - 将 this 传递给回调函数?

标签 javascript node.js

这是我的 Java Script 对象。

HelloObject(server) {
    this.server = server;
    this.socketio = require("socket.io");
}

HelloObject.prototype = {
    constructor: HelloObject,
    listen: function() {
        this.serverProcess = this.socketio.listen(this.server);
        this.serverProcess.sockets.on('connection', this.connect);
    },
    connect: function(socket) {

    }
}

// I am invoking the object

var socketServer = new HelloObject(server)
// Meaning "this" will refer to sockerServer
socketServer.listen()

很抱歉问了一个愚蠢的问题,我是 javascript 的新手。 我需要将“this”传递给 this.connect 函数。 我试过 this.connect.apply(this) ,结果是我丢失了套接字对象。

最佳答案

在回调中,如果你想让connect绑定(bind)到当前对象(this),那么你需要使用Function.prototype.bind函数,像这样

this.serverProcess.sockets.on('connection', this.connect.bind(this));

关于javascript - 将 this 传递给回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752897/

相关文章:

javascript - 如何动态隐藏radiofield extJS

javascript - 使用 appendchild 方法添加具有特定样式的元素

javascript - 如何在滚动条上旋转背景图片

javascript - PHP 中的 Node.js console.time() 等效吗?

node.js - 蒙戈数据库 |从文档数组中删除对象

javascript - 在播放器上的浏览器上播放 wav 字节数据

javascript - 我的 React 选项卡代码运行良好,但我需要更改 html 结构

node.js - XML解析的最佳 Node 模块

node.js - 如何在 Node.js 中使用 k6

mysql - Sequelize 错误 : you must use the 'as' keyword to specify the alias of the association you want to include. - node.js