JS:绑定和函数链

JS: bind and function chaining

本文关键字:函数 绑定 JS      更新时间:2023-09-26

我找到了以下代码:

  this.element.click((function() {
    // some logic
  }).bind(this));

这是另一个例子:

render: function () {
    this.getAsyncData(function () {
        this.specialFunction();
        this.anotherSpecialFunction();
    }.bind(this));
}

据我了解,这是函数链,是吗?这是一个例子,据我了解,为了使用链,我们 nete 前一个函数来返回一些东西。我的意思是

var gmap = function() {
    this.add = function() {
        alert('add');
    return this; //HERE WE RETURN
    }
    this.del = function() {
       alert('delete');
       return this; //HERE WE RETURN
    }
}
var test = new gmap();
test.add().del();

你能解释一下绑定如何在以前的函数中不返回的情况下工作吗?

在这种情况下,bind不是jQuery的事件绑定器。它设置this将在单击处理程序中显示的内容。

function Cat() {
  this.name = 'Gordon';
  this.element = $('#someEl');
  this.element.click((function() {
    console.log(this.name);  // logs Gordon
  }).bind(this));
}

我们将this绑定到Cat,以便我们可以处理Cat的属性,例如name。所以这与链接无关。

MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind小提琴:http://jsfiddle.net/c4phfs8s/

.bind(Function对象的一种方法,它有效地做到了这一点:

function bind(that) {
  var self = this;
  return function () { 
     return self.apply(that, arguments); 
  };
}

看到.bind(返回一个函数,该函数在调用时将给定的参数应用于使用先前给定this调用.bind(的函数。

.

bind() 允许您将对象绑定到函数,因此如果您在函数中使用关键字"this",则 'this' 将是该对象

function test () {
this.a = 'hello';
this.b = 'world';
}
var callNewTest = new test;
(function test2 () {
console.log(this, this.a, this.b)
}).bind(callNewTest)

如果你在谈论jQuery的.bind()方法,文档声明它是用来附加事件侦听器的,但在你给出的示例中,它使用了上面的解释。