2017-11-04 100 views
0

我將對象文字添加到原型。我通過獲取對象的屬性並將值放入數組來完成此操作。然後我使用構造函數創建一個新對象,並將數組作爲參數。爲什麼應用跳過用於參數的數組的第一個元素?

唯一的問題是構造函數(使用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

爲什麼你有一個參數給你的函數調用'undefined'? –

+0

老習慣,只是爲了確保'未定義'實際上意味着'未定義'。這可能不是必要的,我只是以這種方式來學習。 – Cuckoo

回答

1

試試這個

root['room_' + index] = new (Function.prototype.bind.apply(Room, convertArray))(); 

或現代的JavaScript

root['room_' + index] = new Room(...convertArray) 
+0

謝謝。這絕對是更整潔。但是輸出仍然是錯誤的。 '位置'值應該是一個數字。與我應用於構造函數的數組中的第一個元素相同。 實際上,現代版本修復了這個問題,但奇怪的是沒有將索引號添加到變量名中。 – Cuckoo

+0

它是我的所有測試中的代碼 –

+0

對不起,我沒有正確閱讀它。現代版本完美運作。謝謝。我不明白是什麼導致了我的版本中的問題。 – Cuckoo

1

Room.bind.apply(Room, convertArray)是問題。您是bind函數,而不是直接構造函數。由於綁定需要this作爲第一個參數,因此apply也必須提供兩次。

喜歡的東西

Function.bind.apply(Room, [null].concat(convertArray)) 

應該工作。

Relevant Mozilla docs

+0

啊,謝謝。現在明白這個問題,真的讓我很困惑,非常感謝。 – Cuckoo

相關問題