将回调函数与原型函数一起使用

Using callback function with prototype functions

本文关键字:函数 一起 回调 原型      更新时间:2023-09-26

我在进行回调时无法弄清楚如何传递对象方法而不是对"通用原型"方法进行排序。

function Client() {
    this.name = "hello";
}
Client.prototype.apiCall = function(method, params, callback) {
    callback();
}

Client.prototype.onLogin = function(error, data) {
    console.log(this.name);// undefined!!!!
}
Client.prototype.start = function() {
    var self = this;
    self.apiCall('rtm.start', {
    }, self.onLogin) // passing of method like this does not work.
}

我正在传递 onLogin 方法,但它不起作用。这是我重写的代码。以前我将所有方法嵌套在客户端函数中,但是,我了解到这不是这样做的方法,所以现在我正在尝试使用原型。

我知道有一些解决方案"绑定"了 Client(( 函数中的 onLogin 函数,但我想了解这个问题。

您需要

使用 bindapiCall的上下文绑定到回调:

Client.prototype.apiCall = function(method, params, callback) {
    var bound = callback.bind(this);
    bound();
}

否则,onLogin内的 this 将设置为全局对象。

有关更多详细信息,请参阅调用、应用和绑定。

基本上.bind(obj)返回一个函数,当调用该函数时,该函数将在内部使用 (obj) 作为this
因此,您创建此绑定,然后调用它。

您可以使用

callapply来绑定this,请参阅代码片段。出于演示目的,我修改了您的代码。希望它能为您澄清事情

function Client() {
  this.name = "hello";
}
Client.prototype = {
  apiCall: function(method, params, callback) {
    try {
      var trial = method.call(this, params);
      callback.apply(this, [null, trial]);
    } catch (e) {
      callback.apply(this, [e, null]);
    }
  },
  onLogin: function(error, data) {
    if (error) {
      Helpers.report('<b style="color: red">' +
        'An error occured!</b> <i>' +
        error.message + '</i>')
    } else {
      Helpers.report(this.name, ' (data.result = ' + data.result + ')');
    }
  },
  start: function() {
    Helpers.useCSS(1);
    
    // error from this.rtm.start
    Helpers.report('Command: <code>', 'this.apiCall(this.rtm.start, {will: ''not work''}, this.onLogin);','</code>');
    this.apiCall(this.rtm.start, {will: 'not work'}, this.onLogin);
    // this.rtm.works is ok
    Helpers.report('<br>Command: <code>',
                   'this.apiCall(this.rtm.works, {will: ''work''}, this.onLogin);',
                   '</code>');
    this.apiCall(this.rtm.works, {
      will: 'work'
    }, this.onLogin);
  },
  // --------------------------------
  // added rtm for snippet demo
  rtm: {
    start: function(params) {
      return anerror;
    },
    works: function(params) {
      return {
        result: 'worked, <code>params: ' + JSON.stringify(params) + '</code>'
      };
    }
  },
};
new Client().start(); //<= here
<script src="https://rawgit.com/KooiInc/Helpers/master/Helpers.js"></script>