Return to Snippet

Revision: 55928
at February 29, 2012 21:05 by viskenxp


Initial Code
/**
 * This way we can add defaults to a function:
 * var a = function(a, b) {
 *   // code
 * }.defaults(default_a, default_b);
 */
Function.prototype.defaults = function() {
  var _f = this,
      _l = _f.length - arguments.length,
      _a = new Array(_l>0?_l:0).concat(Array.prototype.slice.apply(arguments));

  return function() {
    var i = 0,
        args = Array.prototype.slice.apply(arguments).concat(_a.slice(arguments.length, _a.length));

    for (;i < args.length; i++) {
      if ($.isPlainObject(args[i])) {
        args[i] = $.extend(true, {}, _a[i], arguments[i]);
      }
    }

    return _f.apply(_f, args);
  };
};

Initial URL

                                

Initial Description
This snippet uses jQuery.extend() to merge the objects.

Initial Title
JavaScript Function Default Arguments (Full Object Merge)

Initial Tags
javascript, function

Initial Language
JavaScript