从同一类中的另一个方法调用 java 脚本类内的方法

Call a method inside a java-script class from another method inside the same class

本文关键字:方法 另一个 调用 java 脚本 一类      更新时间:2023-09-26

我正在尝试创建自己的类,因此维护可能会容易得多,但我有问题,这是我的代码:

var SonalScript = function() {
console.log('instance created');
    this.AjaxCall = function(url,data){
      $.post(url,data,function(data,status){
            alert("Data: " + data + "'nStatus: " + status);
          });
}
this.Switches = function(ElemIdentifier) {
    $(ElemIdentifier).bootstrapSwitch();
    $(ElemIdentifier).on('switchChange.bootstrapSwitch', function(event, state) {
        //  console.log( $(this).get('name'));
        var ModuleName = $(this).attr("name");
        var name = $(this).data("name") ;
        var BtnValue = $(this).data("value") ;
        var url = $(this).data("addr") ;
        var BtnResult = '';
        if (state) {
        // data-addr
        // data-name
        // data-value
        // result = True Or False
        BtnResult = 'True';
        //  alert('Enabling : ' + ModuleName );
        } else {
         BtnResult = 'False';
        //  alert('Disabling : ' + ModuleName);
        }
      //  alert(result);
        var data = { name:BtnValue , result : BtnResult };
        console.log(data);
        console.log(url);
        this.AjaxCall(url,data); // << Problem is exactly this line
    });
  }

};
 SonalUtil = new SonalScript();

当我尝试呼叫时: 这。AjaxCall(url,data);然后我在控制台中收到此错误:

 Uncaught TypeError: undefined is not a function

你觉得怎么样?是什么导致了错误?

有两种

方法可以做到这一点,一种是将this绑定到回调,另一种是将this放入回调功能的闭包上下文中。所以第一种方法是:

...
this.Switches = function(ElemIdentifier) {
    $(ElemIdentifier).bootstrapSwitch();
    $(ElemIdentifier).on('switchChange.bootstrapSwitch', function(event, state) {
        ...
    }.bind(this));
  }
...

第二个将是

....
var self = this;
$(ElemIdentifier).on('switchChange.bootstrapSwitch', function(event, state) {
        //  console.log( $(self).get('name'));
        var ModuleName = $(self).attr("name");
        var name = $(self).data("name") ;
        var BtnValue = $(self).data("value") ;
        var url = $(self).data("addr") ;
        var BtnResult = '';
        if (state) {
        // data-addr
        // data-name
        // data-value
        // result = True Or False
        BtnResult = 'True';
        //  alert('Enabling : ' + ModuleName );
        } else {
         BtnResult = 'False';
        //  alert('Disabling : ' + ModuleName);
        }
      //  alert(result);
        var data = { name:BtnValue , result : BtnResult };
        console.log(data);
        console.log(url);
        self.AjaxCall(url,data); // << Problem is exactly this line
    });
...