我找到了以下代码:
this.element.click((function() {
// some logic
}).bind(this));
和here是另一个例子:
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this));
}
据我了解,它是函数链接,对吗? Here是一个例子,据我所知,为了使用链,我们需要前面的函数返回一些东西。我是说
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 在之前的函数中没有 return 的情况下是如何工作的吗?
最佳答案
bind
,在这种情况下,不是 jQuery 的事件绑定(bind)器。它设置点击处理程序中的this
。
function Cat() {
this.name = 'Gordon';
this.element = $('#someEl');
this.element.click((function() {
console.log(this.name); // logs Gordon
}).bind(this));
}
我们将 this
绑定(bind)到 Cat
,这样我们就可以使用 Cat
的属性,比如 name
。
所以这与链接无关..
MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind fiddle :http://jsfiddle.net/c4phfs8s/
关于javascript - JS : bind and function chaining,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27510585/