Viet Nguyen Viet Nguyen - 5 months ago 13
Javascript Question

Error creating and accessing object array

Given the following declaration

function Func1(a, b) {
this.a = a;
this.b = b;
};


I'd like to create a place holder for an array of Func1 object. As far I as I see, i declared an array of items so it should have already been defined. But every time I tried to access the array, it gives me the "undefined" error.

var Func2 = function () {
var items = [];

this.addItem = function (a, b) {
items.push(new Func1(a, b));
}

var function2 = new Func2();
function2.addItem(2, 'test');
window.alert(function2.items[0].b); // this gives error "Unable to get property '0' of undefined or null reference. I'd like to be able to show 'test' here.


I also modified the code as to use declare 'this.items = []' instead of 'var items=[]', it gives me a different error, as follows:

var Func3 = function () {
this.items = [];

this.addItem = function (a, b) {
items.push(new Func1(a, b)); // this gives error 'items' is undefined
}
};

var function3 = new Func3();
function3.addItem(3, 'test');
window.alert(function3.items[0].b); // I want to show 'test' here


I modified the addItem function again, still get error

var Func4 = function () {
this.items = [];

this.addItem = function (a, b) {
items[items.length] = new Func1(a, b); // this gives error 'items' is undefined, too
}
};


I just couldn't find out why the code was failing, and Google search didn't help me much. I could have not used the right keyword to search but searching for "accessing array in javascript" doesn't give me any good result. I'd appreciate any help.

Answer

You should use this.items instead of just items. There is no global or local variable defined as items in the posted code and this is why you get such error.

this.items.push('...');

When you use var items = []; in the constructor, the variable is local to the constructor function, so external scope can't access the variable. You should either define a method that returns the value or define the items as an instance (object) property.

These are 2 options:

var Option1 = function () {
    var items = [];

    this.addItem = function (a, b) {
       items.push(new Func1(a, b));
    }

    this.getItems = function() {
       return items;
    }
}

And:

var Option2 = function () {
    this.items = [];

    this.addItem = function (a, b) {
       this.items.push(new Func1(a, b));
    }
}
Comments