javascript - JS : bind and function chaining

标签 javascript

我找到了以下代码:

  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/

相关文章:

javascript - Jasmine 中的 SpyOn javascript 数组函数

javascript - 左侧带有导航栏的 jquery ui 标签页

php - Javascript 日期验证(范围)

javascript - 怎么才能停止我的动画圈呢? - JS

javascript - Chrome 中的 json-server "Access to localhost was denied"

javascript - 为什么 npm run serve 在 Vue.js 上构建缓慢?

javascript - 我如何像在 jquery 中一样遍历 Prototype 中的隐藏 div?

Javascript string.replace 为 html 字符串

javascript - 如何在 CSS 的可调整大小的空间中排列不同长度的元素?

javascript - 'class'实例创建时的回调