我是ES5的Function.prototype.bind和currying参数(基本上是为函数创建默认参数)的忠实粉丝。

我当时在鬼混,但是我无法为自己的生活弄清楚自己的构造。这是我的游乐场:

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'}对象到底如何作为this中的foo的引用。据我了解,我们正在创建对Function.prototype.call的绑定(bind)调用。让我们快速检查MDN概要以了解.bind():
fun.bind(thisArg[, arg1[, arg2[, ...]]])

因此,thisArg.callhello函数,其后是参数列表。基本上会发生什么
Function.prototype.call.call( hello, {what: 'dafuq'}, 2);

...呃,现在我的大脑有点痛了。我想我现在知道会发生什么,但是请有人找些好话来详细解释它。
  • {what: 'dafuq'}如何成为this reference
  • 最佳答案



    这是因为foo实际上是call方法,绑定(bind)了hello函数作为调用上下文,并绑定(bind)了该对象作为第一个参数。 .call的第一个参数设置其调用上下文的调用上下文。既然已绑定(bind)它,则意味着该对象始终是调用上下文。

    这样说吧...

    您已将.call的调用上下文绑定(bind)到hello

    这实际上与做...

       hello.call();
    // or...
    // Function.prototype.call.call(hello);
    

    您还已经将.call的第一个参数绑定(bind)到{what: "dafuq"},因此实际上与执行此操作相同...
    hello.call({what: "dafuq"});
    // or...
    // Function.prototype.call.call(hello, {what: "dafuq"});
    

    最后,您已经将.call的第二个参数绑定(bind)到2,因此这实际上与执行此操作相同...
    hello.call({what: "dafuq"}, 2);
    // or...
    // Function.prototype.call.call(hello, {what: "dafuq"}, 2);
    

    10-06 04:21
    查看更多