webdad3
webdad3

Reputation: 9080

calling function from prototype function

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?

Upvotes: 0

Views: 198

Answers (1)

Bergi
Bergi

Reputation: 664538

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);

Upvotes: 1

Related Questions