function-bind.js 1.1 KB

123456789101112131415161718192021222324252627
  1. 'use strict';
  2. var aFunction = require('../internals/a-function');
  3. var isObject = require('../internals/is-object');
  4. var slice = [].slice;
  5. var factories = {};
  6. var construct = function (C, argsLength, args) {
  7. if (!(argsLength in factories)) {
  8. for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
  9. // eslint-disable-next-line no-new-func -- we have no proper alternatives, IE8- only
  10. factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')');
  11. } return factories[argsLength](C, args);
  12. };
  13. // `Function.prototype.bind` method implementation
  14. // https://tc39.es/ecma262/#sec-function.prototype.bind
  15. module.exports = Function.bind || function bind(that /* , ...args */) {
  16. var fn = aFunction(this);
  17. var partArgs = slice.call(arguments, 1);
  18. var boundFunction = function bound(/* args... */) {
  19. var args = partArgs.concat(slice.call(arguments));
  20. return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args);
  21. };
  22. if (isObject(fn.prototype)) boundFunction.prototype = fn.prototype;
  23. return boundFunction;
  24. };