我將對象文字添加到原型。我通過獲取對象的屬性並將值放入數組來完成此操作。然後我使用構造函數創建一個新對象,並將數組作爲參數。爲什麼應用跳過用於參數的數組的第一個元素?
唯一的問題是構造函數(使用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);
爲什麼你有一個參數給你的函數調用'undefined'? –
老習慣,只是爲了確保'未定義'實際上意味着'未定義'。這可能不是必要的,我只是以這種方式來學習。 – Cuckoo