Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript how can I call one prototype method in another prototype method?

suppose I have a function:

function test(){}

test.prototype.method01=function(){
    //do something
}

test.prototype.method02=function(){
    //how can I call the method01?
    //this.method01()...?
    //but the chrome through an error:
    //Uncaught TypeError: Object #<HTMLImageElement> has no method 'method01'
}

Edited: in fact the method01 like this:

test.prototype.method02=function(){
    $('.cpy').resizable({

    }).draggable({
        start:function(e,ui){
            this.method01();
        }
    });
}
like image 913
hh54188 Avatar asked Mar 17 '12 12:03

hh54188


1 Answers

test.prototype.method02=function(){
    var testThing = this;
    $('.cpy').resizable({

    }).draggable({
        start:function(e,ui){
            testThing.method01();
        }
    });
}

You have to preserve the this reference in another local variable so that the callback function can use it when calling the other method. The this reference is bound upon each and every function call, including calls to callback functions like the one you're using in the ".draggable()" setup. When that's called this will be set to something different from the this in your "method02" function.

like image 143
Pointy Avatar answered Nov 13 '22 18:11

Pointy