Skip to content

Instantly share code, notes, and snippets.

@abozhilov
Created November 3, 2011 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abozhilov/1336141 to your computer and use it in GitHub Desktop.
Save abozhilov/1336141 to your computer and use it in GitHub Desktop.
Cross browser default parameter values.
var def = (function () {
var PROTO_SUPPORT = !{__proto__ : null}.toString,
hasOwnP = {}.hasOwnProperty;
var def;
if (PROTO_SUPPORT) {
def = function (params, func) {
return function (args) {
args.__proto__ = params;
func.call(this, args);
};
};
}
else {
def = function (params, func) {
return function (args) {
for (var i in params) {
if (hasOwnP.call(params, i) && !hasOwnP.call(args, i)) {
args[i] = params[i];
}
}
func.call(this, args);
};
};
}
return def;
})();
//Example
var f = def({foo : 10, bar : 20 }, function (args) {
print(args.foo, args.bar);
});
f({}); //10 20
f({foo : 50}); //50 20
f({foo : 50, bar : 50}); //50 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment