gpt4 book ai didi

javascript - 如何删除 Node.JS 中的对象?

转载 作者:行者123 更新时间:2023-12-03 08:00:21 24 4
gpt4 key购买 nike

我决定从简单的聊天开始。其实是有问题的。所以,我有一个对象ChatServer,它实现了创建socket.io的对象,并与连接和断开客户端一起工作。

"use strict";

var SocketServer = require('socket.io')
, Client = require('./Client.js');

class ChatServer {
constructor(app, http) {
var io = SocketServer(http)
, clients = {};

io.on('connection', function(socket) {
console.log('Client ' + socket.id + ' connected');

clients[socket.id] = new Client(app, socket);

socket.on('disconnect', function() {
console.log('Client ' + socket.id + ' disconnected');

clients[socket.id] = undefined;
delete clients[socket.id];
});
});
}
}

module.exports = ChatServer;

连接时,会创建客户端对象 Client,该对象为该特定客户端实现消息处理。

"use strict";

class Client {
constructor(app, socket) {
this.app = app;
this.socket = socket;

this.app.on('chat.sendMessage', this.sendMessage.bind(this));
}

sendMessage(message) {
console.log('Client ' + this.socket.id + ' on chat.sendMessage');
this.socket.emit('chat.sendMessage', message);
}
}

module.exports = Client;

app - 它是EventEmitter,它定期发布“chat.sendMessage”(用于测试),在客户端对象中,消息被接收并发送给浏览器。

但是,如果客户端断开连接,客户端对象不会消失,而是继续捕获消息并将其发送到断开连接的套接字。

Client ZbEFj8ykXba9CxLiAAAA connected
Client ZbEFj8ykXba9CxLiAAAA on chat.sendMessage
Client ZbEFj8ykXba9CxLiAAAA on chat.sendMessage
Client ZbEFj8ykXba9CxLiAAAA on chat.sendMessage
Client ZbEFj8ykXba9CxLiAAAA on chat.sendMessage
Client ZbEFj8ykXba9CxLiAAAA on chat.sendMessage
Client ZbEFj8ykXba9CxLiAAAA disconnected
Client ZbEFj8ykXba9CxLiAAAA on chat.sendMessage
Client ZbEFj8ykXba9CxLiAAAA on chat.sendMessage
Client ZbEFj8ykXba9CxLiAAAA on chat.sendMessage
Client ZbEFj8ykXba9CxLiAAAA on chat.sendMessage

我可能不完全理解销毁对象的机制,我知道它需要删除对它的所有引用,这里就完成了。

clients[socket.id] = undefined;
delete clients[socket.id];

但是,这不起作用。我做错了什么?

最佳答案

你不需要给数组元素分配undefined,一旦你删除它就会变成undefined

delete clients[socket.id];

实际上,当您使用 var 关键字时,它会附加名为“VariableEnvironment”的变量当前范围

在这种特殊情况下,尽量避免使用 var 关键字

了解更多信息http://www.ecma-international.org/ecma-262/5.1/

关于javascript - 如何删除 Node.JS 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607494/

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