Diving Into Lodash: Once Method

Next on list is 'once' method.

/**
 * Creates a function that is restricted to execute `func` once. Repeat calls to
 * the function will return the value of the first call. The `func` is executed
 * with the `this` binding of the created function.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new restricted function.
 * @example
 *
 * var initialize = _.once(createApplication);
 * initialize();
 * initialize();
 * // `initialize` executes `createApplication` once
 */
function once(func) {
  var ran,
      result;

  return function() {
    if (ran) {
      return result;
    }
    ran = true;
    result = func.apply(this, arguments);

    // clear the `func` variable so the function may be garbage collected
    func = null;
    return result;
  };
}

and now line by line:

  1. func = null;

    Smartly nullifying the function so the function may be garbage collected

It's important to nullify unused variable in a particular function, so that unnecessary memory usage is avoided.

That's it! from this method.

This entry was published on 25th Mar, 2013.