var unboundSlice = Array.prototype.slice; var slice = Function.prototype.apply.bind(unboundSlice); // 这里的Function.prototype.apply 其实就是apply函数 slice(arguments); // 等同于 apply.bind(unboundSlice); 也就是slice === Array.prototype.slice
假如不支持bind的时候
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Does not work with `new (funcA.bind(thisArg, args))` if (!Function.prototype.bind) (function(){ var slice = Array.prototype.slice; Function.prototype.bind = function() { var thatFunc = this, thatArg = arguments[0]; // 缓存调用函数,this指向,其它参数 var args = slice.call(arguments, 1); if (typeof thatFunc !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function thrownewTypeError('Function.prototype.bind - ' + 'what is trying to be bound is not callable'); } returnfunction(){ var funcArgs = args.concat(slice.call(arguments)) // 其它参数合并传入参数,并成统一的函参 return thatFunc.apply(thatArg, funcArgs); }; }; })();