Moon
Moon

Reputation: 22565

How to invoke a prototype function within same object?

I have the following javascript code.

var Test = function(){



    $("#"+elementId).click(function(){
        // How to call Test.callbackTest here?
    });

}

Test.prototype.callbackTest = function(){
    //code
}

If I want to call callbackTest() in clicking event, do I have to use this.callbackTest()?

or is there any better ways?

Upvotes: 1

Views: 249

Answers (2)

Rizwan Sharif
Rizwan Sharif

Reputation: 1119

If you want to use from click function , this.callbackTest() wont work as this will be bound to window object and not your functions. There are various ways to do so .. one quick one

    var Test = function(){

       var that = this

        $("#"+elementId).click(function(){
            // How to call Test.callbackTest here?
             that.callbackTest();
        });

    }

    Test.prototype.callbackTest = function(){


  //code
}

jquery also provides a proxy solution , i recommend you check it out. if you use it your code will be like

  var Test = function(){

        $.proxy(this.callbackTest,this) // This ensures that wheneven callbackTest is called , 'this' inside callbackTest will be bound to current object , in this case Test 
        $("#"+elementId).click(function(){
            //AND THEN YOU CAN USE THIS here 
             this.callbackTest();
        });

    }

    Test.prototype.callbackTest = function(){


  //code
}

Upvotes: 3

KooiInc
KooiInc

Reputation: 122936

You can make callbackTest private:

var Test = function(){
   function callbackTest(){
      //code
   }

   $("#"+elementId).click(callBackTest);
};

Otherwise it should be

var Test = function(){
   var me = this;
   $("#"+elementId).click(function(){
        me.callbackTest();
   });
};

Upvotes: 1

Related Questions