对不起,我不确定究竟要搜索什么,因为我确信之前已经回答了这个问题但是这里有。我有一个使用nodejs的网络聊天服务器,我制作了一个播放器类,但是如果我将播放器类推送到包含所有用户的播放器数组并更新播放器类(如player.id),则更改不会出现在播放器数组中。我该如何解决这个问题?
var User = require('./User.js');
var wsID = 1; // should be random just for this example
var USERS = {};
USERS[wsID] = {
socket: "",
clientDetails: {
username: "",
isGuest: ""
}
}
user = new User();
user.setUsername("test");
USERS[wsID].username = user.getUsername; // works perfectly
user.setUsername("updatedit"); // fails to update array
console.log(USERS[wsID].username); // returns test and not updatedit...
类文件:
var wsId,
socket,
username,
isGuest;
function User() {
}
User.prototype.getUsername = function(){
return this.username;
}
User.prototype.setUsername = function(name){
this.username = name;
}
module.exports = User;
答案 0 :(得分:0)
执行此操作时,您缺少参考:
USERS[wsID].username = user.getUsername;
那是因为您正在将属性的当前值克隆到另一个对象中。解决此问题的一种方法是更改代码,以便携带实例" user"在你的" clientDetails"所以它不断更新:
user = new User();
user.setUsername("test");
USERS[wsID].clientDetails = user; // carry the entire instance
user.setUsername("updatedit");
console.log(USERS[wsID].clientDetails.username); // should return "updatedit"