2017-11-04 106 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

相关问题