【发布时间】:2019-04-14 13:44:45
【问题描述】:
YDKJS 这本书包含一个描述soft binding utiliy 的部分:
if (!Function.prototype.softBind) {
Function.prototype.softBind = function(obj) {
var fn = this,
curried = [].slice.call( arguments, 1 ),
bound = function bound() {
return fn.apply(
(!this ||
(typeof window !== "undefined" &&
this === window) ||
(typeof global !== "undefined" &&
this === global)
) ? obj : this,
curried.concat.apply( curried, arguments )
);
};
bound.prototype = Object.create( fn.prototype );
return bound;
};
}
我无法理解这条线:curried.concat.apply( curried, arguments )。为什么我们要将已经柯里化的论点与
arguments 对象,而不是简单地使用 curried 数组:
...
) ? obj : this,
curried
);
};
bound.prototype = Object.create( fn.prototype );
...
【问题讨论】:
-
你了解
bind是如何处理参数的吗? -
这是一个绝对可怕的实现,无论它试图实现什么功能。最好忘记它。
-
不,
bind的工作原理完全相同:const f = console.log.bind(console, "Hello"); f("World"); -
请注意,
curried来自对softBind的调用的arguments(如我的示例中的“Hello”),而另一个arguments来自对绑定函数的调用(就像我的例子中的“世界”)。 -
用现代语法编写(省略了接收者):
function bind(fn, ...args1) { return function(...args2) { return fn(...args1, ...args2); }; }
标签: javascript