Object.create()没有完全创建;

时间:2012-06-19 06:35:21

标签: javascript node.js object

以下是代码:

//Note: x actually isn't defined, I'm pulling it from an external source

var x = [{ name: 'Michael Lovesllamas Lankford',
 created: 1338420951.11,
 laptop: 'pc',
 laptop_version: null,
 userid: '4fc6aed7eb35c14ad6000057',
 acl: 0,
 fans: 1,
 points: 5,
 avatarid: 34 }]

global.UserBase = {
 userid: -1,
 name: "noidea",
 isSuperUser: false,
 isDJ: false,
 laptop: "pc",
 afkWarned: false,
 afkTime: Date.now(),
 droppedTime: null,
 droppedRoom: null,
 songCount: 0,
 mWaitingSongLimit: 0,
 totalSongCount: 0,
 totalHeartCount: 0,
 totalHeartsGiven: 0,
 customGreeting: null,
 bootAfterSong: false,
 joinedTime: Date.now(),
 whiteList: false,
 allowedToReserveSpot: true
};

global.mUsers = {length:0};

global.Register = function(a) {
 for(var i = 0; i < a.length; i++) {
  var sUser = a[i];
  mUsers[sUser.userid] = CreateUser(sUser);
  mUsers.length++;
 }
};

global.CreateUser = function(a) {
 var b = Object.create(UserBase);
 b.userid = a.userid;
 b.name = a.name;
 b.laptop = a.laptop;
 if (a.acl > 0) b.isSuperUser = true;
 return b;
};

Register(x);

现在,问题。而不是mUsers [sUser.userid]成为这个:

'4fc6aed7eb35c14ad6000057': {
 userid: "4fc6aed7eb35c14ad6000057",
 name: "noidea",
 isSuperUser: false,
 isDJ: false,
 laptop: "pc",
 afkWarned: false,
 afkTime: Date.now(),
 droppedTime: null,
 droppedRoom: null,
 songCount: 0,
 mWaitingSongLimit: 0,
 totalSongCount: 0,
 totalHeartCount: 0,
 totalHeartsGiven: 0,
 customGreeting: null,
 bootAfterSong: false,
 joinedTime: Date.now(),
 whiteList: false,
 allowedToReserveSpot: true
}

它变成了这个:

'4fc6aed7eb35c14ad6000057': { 
 userid: '4fc6aed7eb35c14ad6000057',
 name: 'Michael Lovesllamas Lankford',
 laptop: 'pc' 
}

为什么没有将UserBase中其余值添加到对象的任何想法?

3 个答案:

答案 0 :(得分:0)

UserBase位于global对象上,您需要在Register对象上调用global

global.CreateUser = function(a) {
 var b = Object.create(this.UserBase);
 b.userid = a.userid;
 b.name = a.name;
 b.laptop = a.laptop;
 if (a.acl > 0) b.isSuperUser = true;
 return b;
};

global.Register(x);

答案 1 :(得分:0)

这种情况正在发生,因为您只是初始化值 用户身份, 名称和笔记本电脑 看到你的代码:

b.userid = a.userid;
b.name = a.name;  
b.laptop = a.laptop; 

要获得所需的结果,您需要调用Global.Register(x)而不是Register(x)

答案 2 :(得分:0)

Object.create创建一个新对象,并将其prototype设置为您传入的对象。

您的对象正在进行初始化,但您只是在新对象实例上显式设置了一些属性。原型对象(UserBase)中的属性都可以访问,但对象的直接console.log将不会打印它们。

E.g。在运行代码后,执行:

for(var p in mUsers['4fc6aed7eb35c14ad6000057']) {
  console.log(p, mUsers['4fc6aed7eb35c14ad6000057'][p]);
}

打印出来:

userid 4fc6aed7eb35c14ad6000057
name Michael Lovesllamas Lankford
laptop pc
isSuperUser false
isDJ false
afkWarned false
afkTime 1340089066700
droppedTime null
droppedRoom null
songCount 0
mWaitingSongLimit 0
totalSongCount 0
totalHeartCount 0
totalHeartsGiven 0
customGreeting null
bootAfterSong false
joinedTime 1340089066700
whiteList false
allowedToReserveSpot true