_bind.js 903 B

1234567891011121314151617181920212223242526
  1. 'use strict';
  2. var aFunction = require('./_a-function');
  3. var isObject = require('./_is-object');
  4. var invoke = require('./_invoke');
  5. var arraySlice = [].slice;
  6. var factories = {};
  7. var construct = function (F, len, args) {
  8. if (!(len in factories)) {
  9. for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']';
  10. // eslint-disable-next-line no-new-func
  11. factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
  12. } return factories[len](F, args);
  13. };
  14. module.exports = Function.bind || function bind(that /* , ...args */) {
  15. var fn = aFunction(this);
  16. var partArgs = arraySlice.call(arguments, 1);
  17. var bound = function (/* args... */) {
  18. var args = partArgs.concat(arraySlice.call(arguments));
  19. return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
  20. };
  21. if (isObject(fn.prototype)) bound.prototype = fn.prototype;
  22. return bound;
  23. };