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?

webdad3
  • 8,893
  • 30
  • 121
  • 223

1 Answers1

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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    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](http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html). 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 Jul 30 '13 at 12:57
  • @apsillers: Thanks for the link, I had no time to search for a good one. – Bergi Jul 30 '13 at 14:45
  • @apsillers Why isn't `Map.prototype` hoisted? Would this be hoisted `Map.prototype.genValues = function() {}`? – neurosnap Mar 10 '15 at 17:30
  • @neurosnap: Assignments or literals are never hoisted. Only declarations are. – Bergi Mar 10 '15 at 17:32