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);
}
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.
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.
Definition and Usage prototype allows you to add new properties and methods to arrays. prototype is a property available with all JavaScript objects.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With