William Martin
William Martin

Reputation: 118

How come an array inside an instanciated object returns undefined?

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.

Upvotes: 0

Views: 437

Answers (3)

Neil Kistner
Neil Kistner

Reputation: 12353

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: []
    };
}

Upvotes: 1

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

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 = [];
}

Upvotes: 2

aga
aga

Reputation: 29416

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.

Upvotes: 4

Related Questions