【问题标题】:How does this Array.prototype and bind combination replace this arrow function这个 Array.prototype 和 bind 组合如何替换这个箭头函数
【发布时间】:2018-03-11 23:27:39
【问题描述】:

我正在阅读:https://hackernoon.com/functional-javascript-resolving-promises-sequentially-7aac18c4431e

作者在一节中谈到了用

替换第二个箭头函数
Promise.resolve([])
    .then(all => funcs[0].then(result => all.concat(result)))

这个

Promise.resolve([])
    .then(all => funcs[0].then(Array.prototype.concat.bind(all)))

我无法理解这是如何工作的...返回的结果是否作为参数隐式添加到 concat 函数中?

【问题讨论】:

  • 当调用一个期望函数作为参数的函数时,您可以编写一个新函数内联,例如foo(() => {...}) 或传递对现有函数的引用,例如foo(myCallback)。此示例使用bind() 函数来执行后者。但我个人看不出在这种情况下使用bind() 的优势;通常箭头函数更清晰,没有性能下降(至少现在是这样)。
  • 从技术上讲,bind() 调用不是对现有函数的引用,而是返回一个新函数,但它是相同的一般思想 - 使用现有函数而不是内联创建新函数。

标签: javascript ecmascript-6 bind arrow-functions


【解决方案1】:

whatEverMethod.bind(thisValue)this 绑定到thisValue

为了理解,我们可以假设(虽然不是实际上)每个方法调用

obj.method(arg0)

等于

obj.method.apply(obj, arg0)

.apply 的第一个参数明确指出:我正在处理哪个对象(因为在.method 的定义中,您可能会引用一些this 值,例如this.prop0 = 10

bind 的作用非常简单:将this 值绑定到方法调用,这样在调用时,不再使用基于环境的默认this 值。

例如:

let obj0 = {a: 1}
let obj1 = {a: 2}
obj0.change = function(value) {
  this.a = value;
} // when declared, default environment is obj0, since it is a method of obj0

// Now, explicitly bind `this` inside of obj0.change to obj1
let changeFunc = obj0.change.bind(obj1);
// This creates a function that has `this` set to obj1, which has the format changeFunc(value)
changeFunc(10);

console.log(obj1.a) // should be 10, since it is now operating on obj1 (due to binding)

因此,

(Array.prototype.concat.bind(all))(someArr)
// is basically
all.concat(someArr)
// due to having the exactly the same `this` value

我们可能想要这样做的原因可能是all 可能不是一个数组。例如,它可能是一个类似数组的对象,例如函数的arguments,它看起来像一个数组,但缺少常见的数组方法。

【讨论】:

    【解决方案2】:

    bind 对函数进行操作,获取 this 的值并返回一个新函数,该函数调用具有指定 this 值和相同参数的原始函数¹。换句话说,

    Array.prototype.concat.bind(all)
    

    意思

    (...args) => Array.prototype.concat.call(all, ...args)
    

    这是

    (...args) => all.concat(...args)
    

    并且由于传递了一个参数,那就是

    result => all.concat(result)
    

    顺便说一句,没有理由不在这里写箭头函数。它更清晰,没有缺点。

    ¹它也可以添加参数。

    【讨论】:

      【解决方案3】:
      • 您必须知道,函数then 接收函数/回调。
      • 函数bind返回一个附加特定对象作为上下文this的函数。

       Array.prototype.concat.bind(all))
                                   ^
                                   |
                                   +---- This object 'all' will be the context
                                         'this' for the function 'concat'.
      

      所以,函数then 将调用callback(隐式传递all 对象)这是函数bind 返回的新函数,在这种情况下,函数concat 来自数组原型.

      资源

      • Function.prototype.bind()

        bind() 方法创建一个新函数,在调用该函数时,将其 this 关键字设置为提供的值,并在调用新函数时在任何提供的参数之前提供给定的参数序列。

      【讨论】:

        猜你喜欢
        • 2018-12-31
        • 2015-05-02
        • 2017-02-05
        • 1970-01-01
        • 1970-01-01
        • 2017-05-01
        • 2021-12-07
        相关资源
        最近更新 更多