Search code examples
javascriptextending

Can I extend Objects with +/- etc?


I tried extending native Objects using operators. It works. Would there be side effects you can think of?

Number.prototype['+++'] = function(n){
    return this + (2*n);
};

String.prototype['+'] = function(){
    return this += [].slice.call(arguments).join('');
}

alert( 10['+++'](10) ); //=> 30
alert( 'hello '['+']('world ','and ','see you later!') ); 
      //=> hello world and see you later!

see also this jsfiddle


Solution

  • There shouldn't be any side effects to what you're doing. Just keep in mind that you don't call what you're doing "operator overloading," or users of your code might think they can actually use the operators. You may also want to ask yourself, "does this really make writing code any easier?"