_createCtor.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. var baseCreate = require('./_baseCreate'),
  2. isObject = require('./isObject');
  3. /**
  4. * Creates a function that produces an instance of `Ctor` regardless of
  5. * whether it was invoked as part of a `new` expression or by `call` or `apply`.
  6. *
  7. * @private
  8. * @param {Function} Ctor The constructor to wrap.
  9. * @returns {Function} Returns the new wrapped function.
  10. */
  11. function createCtor(Ctor) {
  12. return function() {
  13. // Use a `switch` statement to work with class constructors. See
  14. // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  15. // for more details.
  16. var args = arguments;
  17. switch (args.length) {
  18. case 0: return new Ctor;
  19. case 1: return new Ctor(args[0]);
  20. case 2: return new Ctor(args[0], args[1]);
  21. case 3: return new Ctor(args[0], args[1], args[2]);
  22. case 4: return new Ctor(args[0], args[1], args[2], args[3]);
  23. case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
  24. case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
  25. case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
  26. }
  27. var thisBinding = baseCreate(Ctor.prototype),
  28. result = Ctor.apply(thisBinding, args);
  29. // Mimic the constructor's `return` behavior.
  30. // See https://es5.github.io/#x13.2.2 for more details.
  31. return isObject(result) ? result : thisBinding;
  32. };
  33. }
  34. module.exports = createCtor;