Question

function test() {
    var test_array = [];
}

var arrayList = new Array();
arrayList[0] = new test();
arrayList[0].test_array[0] = "test";

(try it out)

I'm trying to create an array, initialize an object as a member of that array, and then assign a text value to an array inside that object. However the array inside the object gives

TypeError: arrayList[0].test_array is undefined

when I try to assign a string to the inner array. I'm still pretty new to javascript so any tips to best practice in this case would be greatly appreciated.

Was it helpful?

Solution

Statement var test_array = []; creates a local variable which will not be visible outside the scope it is defined within. What you need here is the variable defined as the property of object instance. Use this reference inside your test function:

function test() {
    this.test_array = [];
}

For more information on scopes in JavaScript read the documentation.

OTHER TIPS

var declarations within a constructor don't actually modify the instance. They're just locally-scoped within the constructor function itself.

To define a property of the instance, you have to modify this:

function test() {
    this.test_array = [];
}

Updated Fiddle: http://jsfiddle.net/5t62z/3/

Your function was not returning anything. If you notice my update, I now will return an object with the test_array property.

function test() {
    return {
        test_array: []
    };
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top