bind.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var createWrapper = require('../internal/createWrapper'),
  2. replaceHolders = require('../internal/replaceHolders'),
  3. restParam = require('./restParam');
  4. /** Used to compose bitmasks for wrapper metadata. */
  5. var BIND_FLAG = 1,
  6. PARTIAL_FLAG = 32;
  7. /**
  8. * Creates a function that invokes `func` with the `this` binding of `thisArg`
  9. * and prepends any additional `_.bind` arguments to those provided to the
  10. * bound function.
  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 does not set the "length"
  16. * property of bound functions.
  17. *
  18. * @static
  19. * @memberOf _
  20. * @category Function
  21. * @param {Function} func The function to bind.
  22. * @param {*} thisArg The `this` binding of `func`.
  23. * @param {...*} [partials] The arguments to be partially applied.
  24. * @returns {Function} Returns the new bound function.
  25. * @example
  26. *
  27. * var greet = function(greeting, punctuation) {
  28. * return greeting + ' ' + this.user + punctuation;
  29. * };
  30. *
  31. * var object = { 'user': 'fred' };
  32. *
  33. * var bound = _.bind(greet, object, 'hi');
  34. * bound('!');
  35. * // => 'hi fred!'
  36. *
  37. * // using placeholders
  38. * var bound = _.bind(greet, object, _, '!');
  39. * bound('hi');
  40. * // => 'hi fred!'
  41. */
  42. var bind = restParam(function(func, thisArg, partials) {
  43. var bitmask = BIND_FLAG;
  44. if (partials.length) {
  45. var holders = replaceHolders(partials, bind.placeholder);
  46. bitmask |= PARTIAL_FLAG;
  47. }
  48. return createWrapper(func, bitmask, thisArg, partials, holders);
  49. });
  50. // Assign default placeholders.
  51. bind.placeholder = {};
  52. module.exports = bind;