我将对象文字添加到原型中。我这样做是通过获取对象的属性并将值放在数组中。然后我使用构造函数创建一个新对象,并将数组作为参数。
唯一的问题是构造函数(使用apply)在创建新对象时跳过数组中的第一个元素,因此将错误的值分配给新对象中的错误属性 - 最后一个值为空
在调试器中,数组和构造函数都以正确的顺序显示属性/元素。然而输出是不正确的。
我知道我可以直接将参数放在新的对象构造函数中来创建新对象。但这很难理解。除非有另一种方法将物体附加到原型上?或者是一种更整洁的方式来安排我的数据,为构造函数做好准备?
以下是代码:
(function(root, undefined) {
var roomArray = [
{
locationIndex: 0,
name: "North room",
description: "The room is bare, there is a smashed window on the North wall, beyond which you see a grey mist.",
exits: {north: false, south: 1, east: false, west: false, down: false, up: false}
},
{
locationIndex: 1,
name: "Room 1",
description: "It is hard to see much here.",
exits: {north: 0, south: 3, east: 2, west: false, down: false, up: false}
},
{
locationIndex: 2,
name: "Room 2",
description: "A bedroom.",
exits: {north: false, south: false, east: false, west: 1, down: false, up: false}
},
{
locationIndex: 3,
name: "kitchen",
description: "A kitchen.",
exits: {north: 1, south: false, east: false, west: false, down: false, up: false}
}
];
// Room constructor
function Room(location, name, description, exits) {
this.location = location;
this.name = name;
this.description = description;
this.exits = exits;
}
// Create Rooms
roomArray.forEach(function(room, index) {
var convertArray = [];
for (var props in room) {
convertArray.push(room[props]);
}
eval("room_" + index + " = new (Room.bind.apply(Room, convertArray))()");
console.log(convertArray);
console.log(eval("room_" + index))
});
})(this);
答案 0 :(得分:1)
试试这个
root['room_' + index] = new (Function.prototype.bind.apply(Room, convertArray))();
或现代javascript
root['room_' + index] = new Room(...convertArray)
答案 1 :(得分:1)
apply
就是问题所在。您是bind
this
函数,而不是直接构造函数。由于bind将apply
作为第一个参数,Function.bind.apply(Room, [null].concat(convertArray))
也是如此,因此您必须提供两次。
像
这样的东西{{1}}
应该有用。