如何在同一对象中调用原型函数

How to invoke a prototype function within same object?

本文关键字:调用 原型 函数 对象      更新时间:2023-09-26

我有以下javascript代码。

var Test = function(){

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

如果我想在点击事件中调用callbackTest(),我必须使用这个.callbackTest(()吗?

或者有更好的方法吗?

如果你想使用from click函数,这个.callbackTest()将无法工作,因为它将绑定到窗口对象,而不是你的函数。有多种方法可以做到这一点。。一次快速一次

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

  //code
}

jquery还提供了一个代理解决方案,我建议您查看一下。如果你使用它,你的代码将像

  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
}

您可以将callbackTest设为私有:

var Test = function(){
   function callbackTest(){
      //code
   }
   $("#"+elementId).click(callBackTest);
};

否则应该是

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