Posted By

viskenxp on 02/29/12


Tagged

javascript default function defaults arguments


Versions (?)

JavaScript Function Default Arguments (Full Object Merge)


 / Published in: JavaScript
 

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

  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
Posted By: viskenxp on February 29, 2012

This can prob be further optimized by merging line 14 with 16-20.

You need to login to post a comment.