我是 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[, ...]]])
因此,.call
的 thisArg
是 hello
函数,后跟参数列表。基本上是这样的
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/