简体   繁体   English

javascript / jquery-向实例化对象添加属性

[英]javascript / jquery - adding properties to an instantiated object

I am instantiating an object which builds an associative array. 我正在实例化一个建立关联数组的对象。 After it is instantiated, I want to add properties the object's members, but I'm getting an error when I attempt to do so. 实例化之后,我想添加对象成员的属性,但是在尝试添加对象时出现错误。

So this is the object, which parses a bunch of xml and builds out the scenes and vehicles arrays: 因此,这是对象,该对象解析一堆xml并构建场景和车辆数组:

var supertree = {
    scenes: {},
    vehicles: {},
    init: function() {
        this.parseScenes();
        this.parseVehicles();
    },
...

And when I instantiate the object: 当我实例化对象时:

supertree.init();
    supertree.ready = function() {
        assignSpritePos();
    }

I can't add properties to it. 我无法为其添加属性。 This is what I'm trying to do: 这就是我想要做的:

function assignSpritePos(){


    var sceneCount = 0;
    var sceneLength = Object.keys(supertree.scenes).length;

    for (i=0; i< sceneLength; i++){
        //console.log(i);
        supertree.scenes[i].index = i;
        sceneCount++;
    }
}

As you can see, all I'm really trying to do is store some permanent reference to its index in the overall object. 如您所见,我真正想做的就是将一些对其索引的永久引用存储在整个对象中。 How do I do this? 我该怎么做呢? The error I get is: 我得到的错误是:

TypeError: 'undefined' is not an object (evaluating 'supertree.scenes[i].index = i')

Assigning properties to objects isn't recursive, ie it doesn't create objects automagically for you so you must assign each property individually. 为对象分配属性不是递归的,即不会自动为您创建对象,因此您必须分别分配每个属性。

Try this... 尝试这个...

supertree.scenes[i] = { 'index': i };

You can't assign a property to an object that doesn't exist yet. 您无法将属性分配给尚不存在的对象。 Use this: 用这个:

supertree.scenes[i] = {};
supertree.scenes[i].index = i;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM