views:

57

answers:

2
function FakeClass(){};  
FakeClass.prototype.someMethod = function(){};
FakeClass.prototype.otherMethod = function(){
    //need to call someMethod() here.
}

I need to call someMethod from otherMethod, but apparently it doesn't work. If i build it as a single function (not prototyped), i can call it, but calling a prototyped does not work. How can i do it as if i was treating the function just like a class method?

Update: I'm calling the method after a jQuery event is triggered. Does it affect the way the whole thing behaves?

function CicloviarioEngine(){};

CicloviarioEngine.prototype.test = function(){
    alert("Hey");
}
CicloviarioEngine.prototype.initialize = function(){
    $('#add-route').click(function(){
    this.test(); //doesn't work
    CicloviarioEngine.test(); //doesn't work
    externalTest(); //works 

    });
}

function externalTest(){
    alert("externalTest()");
}
+2  A: 

The members of the prototype will be available on the object instance, so you can simply call the method using the this keyword:

FakeClass.prototype.otherMethod = function(){
  this.someMethod();
};

Check an example here.

CMS
I updated the question... i forgot to mention the jQuery part, sorry. :)
Jorge
+2  A: 

this inside the event handler function is not the same as this in the enclosing initialize function (in fact it will be a reference to the element that has been clicked). The easiest way to deal with this is to save the value of this into a variable, which the event handler will have access to from its enclosing scope:

CicloviarioEngine.prototype.initialize = function() {
    var that = this;
    $('#add-route').click(function(){
        that.test();
    });
};
Tim Down
Works fine. Thank you! And thank you @CMS too.
Jorge