【问题标题】:What is the usage of .bind() [duplicate].bind() 的用途是什么 [重复]
【发布时间】:2016-10-29 09:16:47
【问题描述】:

我正在阅读这段代码,但我无法理解.bind() 函数。

有一个函数,在那个函数中我看到了这个语句

 this.layers.forEach(function(d){
           //some logic here
        }.bind(this));

现在,.bind(this) 的用途是什么,它是什么意思,如果不添加它会有什么不同

整个函数是这样的:

get_data: function()
    {
        this.layers = [];

        //more logic

      this.layers.forEach(function(d){
           //some logic here
        }.bind(this));

        return this.layers;

    },

阅读 .bind() 的文档并没有让我明白

【问题讨论】:

标签: javascript


【解决方案1】:

thisArray#forEach 中的上下文将是window,要具有your-own 的上下文(在您的示例中,get_data 的上下文),请使用.bind 而不是callback-function

var obj = {
  foo: function() {
    this.fName = 'NAME';
    [0, 1, 2, 3].forEach(function() {
      console.log('' + this);
      console.log('' + this.fName);
    });
  },
  bar: function() {
    this.fName = 'NAME';
    [0, 1, 2, 3].forEach(function() {
      console.log('' + this.fName);
    }.bind(this));
  }
}
obj.foo();
obj.bar();

【讨论】:

  • 不知道:“Array#forEach 中的这个上下文将是窗口”。因此,当我有一个函数时,该函数中的“this”指向该函数所在的对象。但在数组#foreach 中,this 指向的是窗口?
  • @Michel,这是jQuery对我们的影响;)
  • 它和 jQuery 有什么关系?
  • 哇,这让我很奇怪。当我做.bind(this) 和稍后在 bar 函数中我引用this.fName 时,是同一个实例吗?
  • 我把你的代码拿来玩了,把.bind(this)替换成.bind(otherobject),然后bar函数中的this就是otherobject。来自 C# 这并不容易掌握
猜你喜欢
  • 2012-05-06
  • 2014-08-28
  • 2017-03-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多