bind.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var baseRest = require('./_baseRest'),
  2. createWrap = require('./_createWrap'),
  3. getHolder = require('./_getHolder'),
  4. replaceHolders = require('./_replaceHolders');
  5. /** Used to compose bitmasks for function metadata. */
  6. var WRAP_BIND_FLAG = 1,
  7. WRAP_PARTIAL_FLAG = 32;
  8. /**
  9. * Creates a function that invokes `func` with the `this` binding of `thisArg`
  10. * and `partials` prepended to the arguments it receives.
  11. *
  12. * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
  13. * may be used as a placeholder for partially applied arguments.
  14. *
  15. * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
  16. * property of bound functions.
  17. *
  18. * @static
  19. * @memberOf _
  20. * @since 0.1.0
  21. * @category Function
  22. * @param {Function} func The function to bind.
  23. * @param {*} thisArg The `this` binding of `func`.
  24. * @param {...*} [partials] The arguments to be partially applied.
  25. * @returns {Function} Returns the new bound function.
  26. * @example
  27. *
  28. * function greet(greeting, punctuation) {
  29. * return greeting + ' ' + this.user + punctuation;
  30. * }
  31. *
  32. * var object = { 'user': 'fred' };
  33. *
  34. * var bound = _.bind(greet, object, 'hi');
  35. * bound('!');
  36. * // => 'hi fred!'
  37. *
  38. * // Bound with placeholders.
  39. * var bound = _.bind(greet, object, _, '!');
  40. * bound('hi');
  41. * // => 'hi fred!'
  42. */
  43. var bind = baseRest(function(func, thisArg, partials) {
  44. var bitmask = WRAP_BIND_FLAG;
  45. if (partials.length) {
  46. var holders = replaceHolders(partials, getHolder(bind));
  47. bitmask |= WRAP_PARTIAL_FLAG;
  48. }
  49. return createWrap(func, bitmask, thisArg, partials, holders);
  50. });
  51. // Assign default placeholders.
  52. bind.placeholder = {};
  53. module.exports = bind;