我正在尝试将一个名称空间的内容转储到 javascript 中的另一个名称空间中。我可以直接做到这一点的唯一方法如下:
var CHESSMEN = {
Chariot: function(color) {
return {
color: color,
abbreviation: 'R',
type: 'Chariot'
};
},
Horse: function(color) {
return {
color: color,
abbreviation: 'H',
type: 'Horse'
};
},
Elephant: function(color) {
return {
color: color,
abbreviation: 'E',
type: 'Elephant'
};
},
Advisor: function(color) {
return {
color: color,
abbreviation: 'A',
type: 'Advisor'
};
},
General: function(color) {
return {
color: color,
abbreviation: 'G',
type: 'General'
};
},
Cannon: function(color) {
return {
color: color,
abbreviation: 'C',
type: 'Cannon'
};
},
Soldier: function(color) {
return {
color: color,
abbreviation: 'S',
type: 'Soldier'
};
}
}
Object.freeze(CHESSMEN)
function Game(board) {
for (var piece in CHESSMEN) {
eval('var ' + piece + ' = CHESSMEN.' + piece);
}
if (typeof(board) === 'undefined') {
var board = {
a1: new Chariot('red'),
b1: new Horse('red'),
c1: new Elephant('red'),
d1: new Advisor('red'),
e1: new General('red'),
f1: new Advisor('red'),
g1: new Elephant('red'),
h1: new Horse('red'),
i1: new Chariot('red'),
b3: new Cannon('red'),
h3: new Cannon('red'),
a4: new Soldier('red'),
c4: new Soldier('red'),
e4: new Soldier('red'),
g4: new Soldier('red'),
i4: new Soldier('red'),
a10: new Chariot('black'),
b10: new Horse('black'),
c10: new Elephant('black'),
d10: new Advisor('black'),
e10: new General('black'),
f10: new Advisor('black'),
g10: new Elephant('black'),
h10: new Horse('black'),
i10: new Chariot('black'),
b8: new Cannon('black'),
h8: new Cannon('black'),
a7: new Soldier('black'),
c7: new Soldier('black'),
e7: new Soldier('black'),
g7: new Soldier('black'),
i7: new Soldier('black')
};
}
// et cetera
}
在这里,我使用for in
循环来遍历冻结对象的eval
键,并将这些键及其关联值转储到Game
构造函数的范围内。许多人告诉我不要使用eval
,但我没有看到直接合并命名空间的另一种方法。这不安全吗?将棋子构造函数称为CHESSMEN
对象的属性对我来说会更好吗?