我正在读一本关于编写JavaScript框架的书,并找到了这段代码片段.但我不明白它是如何工作的,特别是bind.bind用法?有人有线索吗?
var bind = Function.prototype.bind;
var apply = bind.bind(bind.apply);
var fn = apply([].concat);
var a = [1, 2, 3], b = [4, [5, 6], 7];
fn(a, b);
//output [1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
elp*_*dev 35
这让我回到了解决和扩展方程式的日子.
1.首先,让我们展开第一个apply函数:
var bind = Function.prototype.bind;
var apply = bind.bind(bind.apply);
var fn = apply([].concat);
Run Code Online (Sandbox Code Playgroud)
转换为:
var apply = Function.prototype.bind.bind(Function.prototype.bind.apply);
var fn = apply([].concat)
Run Code Online (Sandbox Code Playgroud)
2.其次,我们扩展了fn函数:
var fn = Function.prototype.bind.bind(Function.prototype.bind.apply)([].concat);
Run Code Online (Sandbox Code Playgroud)
3.我们现在发明一个js代数规则并用bind.bind...()调用调用替换调用.
实际上,我们根据以下概念实施替代基础:
someFunction.bind(arg1)(arg2) <==> someFunction.call(arg1, arg2)
Run Code Online (Sandbox Code Playgroud)
因此我们可以替换它并得到:
var fn = Function.prototype.bind.call(Function.prototype.bind.apply, [].concat);
Run Code Online (Sandbox Code Playgroud)
4.对于我们的第二个js代数规则,我们设计:
someFn.bind.call(target, ...) <==> target.bind(...).
someFn这里不重要因为我们不调用bind().我们调用call的bind-更换this,这是someFn和它为此被替换target.
因此我们将替换bind.call(target)为target.bind替代方案
var fn = Function.prototype.bind.apply.bind([].concat)
Run Code Online (Sandbox Code Playgroud)
5.如果最后一个排列也在做invocation()我们可以做一个替换,如:
fn([1, 2], [3, 4]) <==> [].concat.apply([1, 2], [3, 4])
Run Code Online (Sandbox Code Playgroud)
但是我们只有没有调用的绑定,我们可以替换它,相当于:
var fn = function (arg1, arg2) {
return [].concat.apply(arg1, arg2);
}
// instead arg1 and arg2 we could use more accurate arguments logic also.
Run Code Online (Sandbox Code Playgroud)
最后结果
var fn = Function.prototype.bind.apply.bind([].concat)
// or
var fn = function (arg1, arg2) {
return [].concat.apply(arg1, arg2);
}
Run Code Online (Sandbox Code Playgroud)
该fn函数接受concat函数并让我们以函数式的方式使用它,而无需从对象中调用它.而不是concat绑定到this主叫方,fn在应用它arg1作为this和arg2作为其他PARAMS来连接来arg1.
fn([1, 2], [3, [5, 6], 4])
// [1, 2, 3, 5, 6, 4]
Run Code Online (Sandbox Code Playgroud)
djf*_*dev 12
因为Function.prototype.bind它本身就是一个函数,所以它继承自己作为一个方法.
通常,bind被称为特定函数的实例方法,但我们可以将其重新绑定Function.prototype.apply并返回更高阶的函数.
一种不那么简洁的写作方式是:
function apply (fn) {
return function (a, b) {
return fn.apply(a, b)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2316 次 |
| 最近记录: |