【问题标题】:Once a function is bound with `bind`, its `this` cannot be modified anymore?一旦函数绑定了`bind`,它的`this`就不能再修改了?
【发布时间】:2017-08-23 10:41:37
【问题描述】:

只是玩了一下JS,我想知道为什么下面的代码输出"foo"而不是"bar"

String.prototype.toLowerCase.bind("FOO").call("BAR")

据我了解,.bind("FOO") 返回一个函数,该函数将具有this"FOO",因此调用.bind("FOO")() 输出"foo"

但是,.call("BAR")"BAR"this 调用函数,所以应该已经输出了"bar"

我哪里错了?

【问题讨论】:

  • String.prototype.toLowerCase.bind("FOO") 返回带有参数“FOO”的函数toLowerCase,如果您执行String.prototype.toLowerCase.bind("FOO")()String.prototype.toLowerCase.bind("FOO").call(),您将得到foo 作为输出。

标签: javascript function call bind


【解决方案1】:

.bind("FOO") 返回一个函数,该函数将具有"FOO" for this

不完全是。它返回一个函数,该函数"FOO" 绑定到this of toLowerCase。它的工作原理是这样的:

function bind(func, thisArg) {
    return function () {
        return func.call(thisArg);
    }
}

您可以根据需要重新绑定返回函数的thiscallfunc(此处:toLowerCase)已经“硬编码”为thisArg(此处:"FOO") .

【讨论】:

    【解决方案2】:

    你是对的。一旦函数与.bind() 绑定,它的this 就不能再被修改。 this.bind() 的第一个参数永久“替换”。

    【讨论】:

      猜你喜欢
      • 2020-04-03
      • 2020-04-16
      • 1970-01-01
      • 2017-05-09
      • 2016-02-22
      • 2020-12-27
      • 1970-01-01
      • 2016-12-22
      相关资源
      最近更新 更多