Function.prototype.binding = function () {
let self = this;
let context = [].shift.call(arguments);
let args = [].slice.call(arguments);
console.log('Function binding args', args);
return function () {
self.apply(context, [].concat.call(args, [].slice.call(arguments)))
}
};
let obj = {
a: 'a'
};
function f(b, c, d) {
console.log(this.a, b, c, d)
}
f.binding(obj, 'b', 'c', 'd')('e');
f.binding(obj, 'b', 'c')('d', 'e');
f.binding(obj, 'b')('c', 'd', 'e');
f.binding(obj)('b', 'c', 'd', 'e');
输出:
Function binding args [ 'b', 'c', 'd' ]
a b c d
Function binding args [ 'b', 'c' ]
a b c d
Function binding args [ 'b' ]
a b c d
Function binding args []
a b c d
Process finished with exit code 0
从输出可以看出 args 是 f.binding 里除了第一个参数剩下所有的参数,而 [].slice.call(arguments) 是 f.binding 后第二个括号里的参数, args 的 this 是 Function.prototype.binding,[].slice.call(arguments) 的 this 是 f.binding(obj)()。