It's not recommended and is never a good idea to augment the built-in classes. Instead, it's better to create your own implementations of built-in classes, a lot like the YUI library does (YArray, etc). However, I'm going to contradict that, because I often find that implementing useful short cuts like this are a benefit to writing clean maintainable code:
if (undefined === Object.prototype.setdefault) {
Object.prototype.setdefault = function(key, def) {
if (! this.hasOwnProperty(key)) {
this[key] = def;
}
return this[key];
};
}
So let's see it in action...
var a = {};
a.setdefault('mylist', []).push(1);
a.setdefault('mylist', []).push(2);
console.log(a.mylist.toString());
1,2
As has been pointed out, it's never a good idea to employ thing = thing || defaultThing
because it only tests non-typed equality of true
, or thing == true
. As opposed to typed equality: thing === true
or thing !== undefined
. So the only way to properly code setdefault
in an inline way would be to use this snippet everywhere:
/* null == thing is equivalent to... */
if (undefined !== thing && null !== thing) {
thing = defaultThing;
}
/* ...but it's not explicit and linters don't like it! */
But as I already said, this just adds bloat to your code and is prone to errors acquired from "copy-and-paste" syndrome.