将函数绑定到此函数的更简洁的方法

Cleaner way to bind a function to this?

本文关键字:函数 方法 简洁 绑定      更新时间:2023-09-26

我有很多代码可以执行以下操作来将回调绑定到this

someMethod: function()
{
  this.doSomething({
    callback: function(a,b,c)
    {
      console.log(a);
      console.log(this.title);
    }.bind(this),
    otherData: [1,2,3,4],
    anotherOption: true
  });
}
title:'test',

我希望这更具可读性,并封装我如何绑定到它 - 通过函数调用或类似的东西......类似于以下伪代码的东西(我知道它不起作用(:

someMethod: function()
{
  this.doSomething({
    callback: this.bind(a,b,c)
    {
      console.log(a);
      console.log(this.title);
    },
    otherData: [1,2,3,4],
    anotherOption: true
  });
},
title:'test',
有没有办法将回调

绑定到这个更易读的回调上?请注意,我上面的例子是简化的 - 通常我可能会传入 2 个回调,以及其他选项。

就个人而言,我会创建回调方法然后分配它,我发现阅读起来不那么痛苦,如果需要,它还会给您留下函数的引用,这在将bind与事件处理程序一起使用时很有用例如(可以添加/删除它们(,因为bind返回一个函数。

someMethod: function() {
  var callback = function(a,b,c) {
    console.log(a);
    console.log(this.title);
  }.bind(this);
  this.doSomething({
    callback: callback 
  });
},
title:'test',

您也根本无法使用bind并且像许多JS方法一样,它采用一个参数,这是回调的范围,因此基本上只是向对象scope: this添加新属性。理想情况下,回调应该使用将范围作为第一个参数的call运行。

怎么样:

someMethod : function ()
{
    var that = this;
    this.doSomething({
        callback : function (a,b,c) {
            console.log(a);
            console.log(that);
        }
    });
}

无论如何,如果您每次都创建一个新函数,则无需.bind。局部变量在这里更合适。

我认为你也可以使用这样的东西:

 //...
 someMethod: function() {
  this.doSomething({
    boundTo: this, //<= here
    callback: function(a,b,c) {
      console.log(a);
      console.log(this.boundTo.title); //<= and here
    },
    otherData: [1,2,3,4],
    anotherOption: true
   })
  }
 // ...

或者这个(关闭(也应该有效

someMethod: function() {
  this.doSomething({
    callback: function(self) {
                return function(a,b,c) {
                  console.log(a);
                  console.log(self.title);
                 }; 
              }(this),
    otherData: [1,2,3,4],
    anotherOption: true
   });
}