简体   繁体   中英

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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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