Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array defined in constructor is undefined in prototype

Tags:

javascript

I'm pretty new to writing OO JS, but this has stumped me. So I setup me new Call object, then define what I assume to be empty arrays. When I call AddFieldQueryToArray() I get

Uncaught TypeError: Cannot call method 'push' of undefined 

On this.fieldArray.push(field)

I don't really know why. I've tried this.fieldArray = fieldArray; in the constructor too.

    function Call() 
    {    
         var fieldArray = new Array();
         var queryArray = new Array();
    }

    Call.prototype.AddFieldQuerysToArray = function(field,query)
    {
        if(field !== 'undefined')
        {               
            this.fieldArray.push(field);
        }

        this.queryArray.push(query);

    }
like image 321
Kikimac Avatar asked Jun 10 '13 09:06

Kikimac


People also ask

Why is my JavaScript array undefined?

You get undefined when you try to access the array value at index 0, but it's not that the value undefined is stored at index 0, it's that the default behavior in JavaScript is to return undefined if you try to access the value of an object for a key that does not exist.

Why is prototype undefined?

JavaScript is a prototype-based language. When a certain property of an object is not found, it will return undefined. This is because it will have found no such property across the prototype chain of the object.

What is the prototype of array function in JavaScript?

Definition and Usage prototype allows you to add new properties and methods to arrays. prototype is a property available with all JavaScript objects.

What is prototype constructor in JavaScript?

constructor. The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.


1 Answers

You should reference instance properties with this. inside the constructor:

function Call() 
{    
     this.fieldArray = [];
     this.queryArray = [];
}

new Array() has a shortcut [] which I have used above.

If you use var fieldArray = []; you would create a local variable which is destroyed once your instance has been created unless you use this kind of construct:

function Call()
{
    var fieldArray = [];

    this.AddFieldQuerysToArray = function(field, query) {
        // ...
        fieldArray.push(field);
    }
}

This creates a closure for each instance in which fieldArray is "kept alive" throughout the instance's lifetime.

like image 67
Ja͢ck Avatar answered Sep 29 '22 23:09

Ja͢ck