function-bind.js 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. var uncurryThis = require('../internals/function-uncurry-this');
  3. var aCallable = require('../internals/a-callable');
  4. var isObject = require('../internals/is-object');
  5. var hasOwn = require('../internals/has-own-property');
  6. var arraySlice = require('../internals/array-slice');
  7. var NATIVE_BIND = require('../internals/function-bind-native');
  8. var $Function = Function;
  9. var concat = uncurryThis([].concat);
  10. var join = uncurryThis([].join);
  11. var factories = {};
  12. var construct = function (C, argsLength, args) {
  13. if (!hasOwn(factories, argsLength)) {
  14. for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
  15. factories[argsLength] = $Function('C,a', 'return new C(' + join(list, ',') + ')');
  16. } return factories[argsLength](C, args);
  17. };
  18. // `Function.prototype.bind` method implementation
  19. // https://tc39.es/ecma262/#sec-function.prototype.bind
  20. module.exports = NATIVE_BIND ? $Function.bind : function bind(that /* , ...args */) {
  21. var F = aCallable(this);
  22. var Prototype = F.prototype;
  23. var partArgs = arraySlice(arguments, 1);
  24. var boundFunction = function bound(/* args... */) {
  25. var args = concat(partArgs, arraySlice(arguments));
  26. return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args);
  27. };
  28. if (isObject(Prototype)) boundFunction.prototype = Prototype;
  29. return boundFunction;
  30. };