I have a prototype function in javascript... I'd like to be able to call another function from that prototyped function.
var objMap = new Map(500,500);
var myCities = objMap.genValues(5);
function Map(sizeX, sizeY) {
this.sizeX = sizeX;
this.sizeY = sizeY;
}
Map.prototype = {
genValues: function (number) {
validateValues(number);
}
}
function validateValues(num){
alert(num);
}
in my console I get the following error:
SCRIPT438: Object doesn't support property or method 'genValues'
When I don't add the function call to validateValues I don't get the error. Is there a way to do this? I'd like to be able to call functions in a recursive manner as well.
UPDATE!
I fixed my code in the following fiddle: I still get the same error.
It sounds like I'm using the prototype functionality/methodology incorrectly as I can't call functions from within that? Is that right?
1 Answer 1
You are constructing the Map instance before you are assigning the prototype; and you're calling the method before you create it. Objects that are instantiated after that assignment would have a genValues method. Two fixes:
function validateValues(num){
alert(num);
}
function Map(sizeX, sizeY) {
this.sizeX = sizeX;
this.sizeY = sizeY;
}
// alter the existing prototype object instead of overwriting it
Map.prototype.genValues = function (number) {
validateValues(number);
}
// create instances only after the "class" declaration is done!
var objMap = new Map(500,500);
var myCities = objMap.genValues(5);
4 Comments
new Map() works before the declaration function Map() { ... } is because function declarations are hoisted to the top of their containing function. However, while the Map constructor is hoisted (and thus Map can be used freely anywhere in the same function as the declaration, before or after), the assignment of Map.prototype is not hoisted, so Map.prototype.genValues is available only after its assignment.Map.prototype hoisted? Would this be hoisted Map.prototype.genValues = function() {}?
}to endgenValues.