0
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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • The test_array variable is only accessible within test(). You have to expose it with "this" – Silkster Jan 13 '14 at 18:52
  • See possible duplicate [Javascript: Do I need to put this.var for every variable in an object?](http://stackoverflow.com/questions/13418669/javascript-do-i-need-to-put-this-var-for-every-variable-in-an-object) for the difference between variables and properties – Bergi Jan 13 '14 at 18:52

3 Answers3

4

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.

aga
  • 27,954
  • 13
  • 86
  • 121
  • When I make this change the I get SyntaxError: missing variable name http://jsfiddle.net/5t62z/4/ – William Martin Jan 13 '14 at 18:58
  • @WilliamMartin: There's no syntax error in this answer. Read and type carefully and double check your work. You're doing `var this.test_array = [];`, which isn't valid. – cookie monster Jan 13 '14 at 18:59
  • @WilliamMartin strange, I've modified your fiddle as I've described and printed the value of `arrayList[0].test_array[0]` via `console.log(arrayList[0].test_array[0])` - it worked as expected. – aga Jan 13 '14 at 19:00
2

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 = [];
}
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
1

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: []
    };
}
Neil Kistner
  • 11,623
  • 2
  • 18
  • 17
  • *"Your function was not returning anything..."* Yes it does. It returns a new object because it was invoked using `new`. http://jsfiddle.net/5t62z/5/ – cookie monster Jan 13 '14 at 18:57