jAn*_*ndy 13 javascript bind partial-application ecmascript-5
我是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 );
Run Code Online (Sandbox Code Playgroud)
此日志输出如下:
hello()
"this" is: Object{ what="dafuq" }
arguments: [2,42]
Run Code Online (Sandbox Code Playgroud)
但是我不明白这个{what: 'dafuq'}物体究竟是如何作为this内部参考的foo.据我所知,我们正在创造一个绑定调用到Function.prototype.call.让我们.bind()快速检查MDN概要:
fun.bind(thisArg[, arg1[, arg2[, ...]]])
Run Code Online (Sandbox Code Playgroud)
所以,thisArgfor .call是hello函数,后跟参数列表.基本上会发生这种情况
Function.prototype.call.call( hello, {what: 'dafuq'}, 2);
Run Code Online (Sandbox Code Playgroud)
...呃现在我的大脑有点疼.我想我现在有了一个想法会发生什么,但请有人找到可靠的单词来详细解释它.
{what: 'dafuq'}变成了this reference你没打电话.bind(thisArg, args),但是
Function.prototype.bind.call(thisArgUsedByCall, thisArgUsedByBind, argument).
显示发生的事情的另一种方式:
// thisArgUsedByCall is a function
Function.prototype.call(thisArgUsedByCall, ...) // does the same as:
thisArgUsedByCall.bind(thisArgUsedByBind, argument);
Run Code Online (Sandbox Code Playgroud)
小智 6
但是我不明白这个
{what: 'dafuq'}对象究竟是如何在foo中作为参考的
这是因为foo有效的call方法是将hello函数绑定为调用上下文,并将该对象绑定为第一个参数.第一个参数.call 设置其调用上下文的调用上下文.既然你已经绑定了它,那就意味着对象永远是调用上下文.
这样说吧......
你已经绑定的调用上下文.call来hello.
这与做......实际上是一样的
hello.call();
// or...
// Function.prototype.call.call(hello);
Run Code Online (Sandbox Code Playgroud)
你也必然的第一个参数.call来{what: "dafuq"},所以这实际上是一样的做...
hello.call({what: "dafuq"});
// or...
// Function.prototype.call.call(hello, {what: "dafuq"});
Run Code Online (Sandbox Code Playgroud)
最后,你已经绑定的第二个参数.call来2,所以这实际上是一样的做...
hello.call({what: "dafuq"}, 2);
// or...
// Function.prototype.call.call(hello, {what: "dafuq"}, 2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1003 次 |
| 最近记录: |