0

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
  • 1
    You are missing a closing } to end genValues. Commented Jul 30, 2013 at 4:30

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

As an addendum for the OP's benefit: the reason 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.
@apsillers: Thanks for the link, I had no time to search for a good one.
@apsillers Why isn't Map.prototype hoisted? Would this be hoisted Map.prototype.genValues = function() {}?
@neurosnap: Assignments or literals are never hoisted. Only declarations are.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.