JavaScript Function Default Arguments (Full Object Merge)


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. /**
  2.  * This way we can add defaults to a function:
  3.  * var a = function(a, b) {
  4.  * // code
  5.  * }.defaults(default_a, default_b);
  6.  */
  7. Function.prototype.defaults = function() {
  8. var _f = this,
  9. _l = _f.length - arguments.length,
  10. _a = new Array(_l>0?_l:0).concat(Array.prototype.slice.apply(arguments));
  11.  
  12. return function() {
  13. var i = 0,
  14. args = Array.prototype.slice.apply(arguments).concat(_a.slice(arguments.length, _a.length));
  15.  
  16. for (;i < args.length; i++) {
  17. if ($.isPlainObject(args[i])) {
  18. args[i] = $.extend(true, {}, _a[i], arguments[i]);
  19. }
  20. }
  21.  
  22. return _f.apply(_f, args);
  23. };
  24. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.