Skip to content

Instantly share code, notes, and snippets.

@kristopher
Last active December 15, 2015 02:09
Show Gist options
  • Save kristopher/5ac8aa85b05fc738247f to your computer and use it in GitHub Desktop.
Save kristopher/5ac8aa85b05fc738247f to your computer and use it in GitHub Desktop.
// myFunc({ a: 1, b: 2, c: 3 })
function myFunc(options) {
var default_options = {
a: 1,
b: 2,
c: 3
}
options = options || {}
for (var key in options) {
if (options.hasOwnProperty(key)) {
default_options[key] = options[key];
}
}
return default_options;
}
// myFunc({ a: 1, b: 2, c: 3 })
function myFunc(options) {
var default_options = {
a: 1,
b: 2,
c: 3
}
return _.extend(default_options, options || {});
}
// myFunc(a = 1, b = 2, c = {})
function myFunc(a, b, c) {
var default_args = [1, 2, {}],
args = Array.prototype.slice.apply(arguments).concat(default_args.slice(arguments.length));
return args;
}
Function.prototype.default_args = function() {
var __method__ = this, __default_args__ = Array.prototype.slice.apply(arguments);
return function() {
return __method__.apply(this, Array.prototype.slice.apply(arguments).concat(__default_args__.slice(arguments.length)));
}
}
var myFunc = function(a, b, c) { console.log(a, b, c); }.default_args(1, 2, {});
// If you don't want to extend the Function prototype
Function.default_args = function(__method__) {
var __default_args__ = Array.prototype.slice.call(arguments, 1);
return function() {
return __method__.apply(this, Array.prototype.slice.apply(arguments).concat(__default_args__.slice(arguments.length)));
}
}
var myFunc = Function.default_args(function(a, b, c) {
console.log(a, b, c);
}, 1, 2, {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment