【发布时间】:2012-08-01 14:11:29
【问题描述】:
我是 ES5 的 Function.prototype.bind 和柯里化参数(基本上是为函数创建默认参数)的忠实粉丝。
我只是在胡闹,但我终其一生都无法弄清楚我自己的构造。这是我的游乐场:
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() 的 MDN 概要:
fun.bind(thisArg[, arg1[, arg2[, ...]]])
所以,thisArg for .call 是 hello 函数,后跟参数列表。基本上发生的事情是这样的
Function.prototype.call.call( hello, {what: 'dafuq'}, 2);
...uuhhh 现在我的大脑有点痛。我想我现在知道会发生什么了,但是请有人找到很好的可靠词来详细解释它。
{what: 'dafuq'}如何变成this reference
【问题讨论】:
标签: javascript bind ecmascript-5 partial-application