javascript - 关于 Function.prototype.bind() 的困惑

标签 javascript bind ecmascript-5 partial-application

我是 ES5 的 Function.prototype.bind 和柯里化(Currying)参数(基本上是为函数创建默认参数)的 super 粉丝。

我有点胡闹,但我再也无法弄清楚自己的构造了。这是我的 Playground :

function hello( arg1, arg2 ) {
    console.log('hello()');
    console.log('"this" is: ', this);
    console.log('arguments: ', arguments);
}

var foo = Function.prototype.call.bind( hello,{what: 'dafuq'}, 2 );
foo( 42 );

日志输出如下:

hello()
"this" is: Object{ what="dafuq" }
arguments: [2,42]

但我不明白 {what: 'dafuq'} 对象到底是如何成为 foo< 中 this 的引用的。据我了解,我们正在为 Function.prototype.call 创建一个绑定(bind)调用。让我们快速检查 .bind() 的 MDN 概要:

fun.bind(thisArg[, arg1[, arg2[, ...]]])

因此,.callthisArghello 函数,后跟参数列表。基本上是这样的

Function.prototype.call.call( hello, {what: 'dafuq'}, 2);

...呃现在我的脑袋有点痛。我想我现在知道会发生什么,但请有人找到很好的实词来详细解释它。

  • {what: 'dafuq'} 如何成为this reference

最佳答案

你不是在调用 .bind(thisArg, args),而是
Function.prototype.bind.call(thisArgUsedByCall,thisArgUsedByBind,参数)

展示发生了什么的不同方式:

// thisArgUsedByCall is a function
Function.prototype.call(thisArgUsedByCall, ...)   // does the same as:
thisArgUsedByCall.bind(thisArgUsedByBind, argument);

关于javascript - 关于 Function.prototype.bind() 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11761145/

相关文章:

javascript - 禁用具有 knockout 条件的悬停

javascript - 没有严格模式的 JSON.parse

javascript - 纯方式修改JS对象

javascript - 具有多个叠加层和图像按钮的 Flowplayer

javascript - vue.js -- 无法通过 css 更改 svg 的样式,并且在 dom 中它应用 element.style 而不是类名

linux - Windows WSL 以上 Linux 中的 AF_UNIX 套接字无法绑定(bind)到/mnt 文件 : error 95, 操作不支持

JavaScript、构造函数和 "this"

javascript - 在 html 文件中显示应用程序脚本文件中的数组

javascript - 如何将输入类型时间的值传递给 Date 对象?

bind - rebol 程序中出现奇怪的 "word has no context"错误