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()");
}
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();
});
};
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.
精彩评论