gpt4 book ai didi

javascript - 一旦一个函数绑定(bind)了 `bind` ,它的 `this` 就不能再修改了吗?

转载 作者:行者123 更新时间:2023-11-29 21:02:28 25 4
gpt4 key购买 nike

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

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

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

但是,.call("BAR")this调用带有"BAR"的函数,所以应该输出"bar"

我哪里错了?

最佳答案

.bind("FOO") returns a function that will have "FOO" for this

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

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

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

关于javascript - 一旦一个函数绑定(bind)了 `bind` ,它的 `this` 就不能再修改了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45837471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com