Andrius Naruševičius
Andrius Naruševičius

Reputation: 8578

Javascript public members inaccessible

I have a pretty easy structure:

var FORMS = [];

function FormObject(type)
{
    this.FormId = FORMS.length;
    //alert(this.FormId); returns results 0 and 1 respectively.
    this.Type = type;
    FORMS.push(FormObject); 
    this.generate = generate();
}

function generate()
{
    return 5;
}

Then I do something like this:

var new_form = new FormObject('fruit');
var another  = new FormObject('vegetable');
alert(another.FormId);//as expected, I get 1 as a result

And then finally try do something like this:

alert(FORMS.length);//result is 2 so I assume the objects got created successfully
alert(FORMS[0]);//prints the whole code of the constructor into the dialog box

However when I try something like this:

alert(FORMS[0].FormId);//result is undefined!!!
alert(FORMS[0].generate());//it shows an error that the object does not have such method

Why is it undefined? I tried reading http://javascript.crockford.com/private.html and it says:

Patterns

Public

function Constructor(...) {
    this.membername = value;
}
Constructor.prototype.membername = value;

Upvotes: 0

Views: 81

Answers (1)

David Hellsing
David Hellsing

Reputation: 108500

Replace:

FORMS.push(FormObject); 

with

FORMS.push(this);

When you push the FormObject object, you are pushing the constructor function, not the instance.

Upvotes: 6

Related Questions