1

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

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 1
    I can't think of any negative side effects, but, I would ask myself, does this actually make code easier to write/read? I would argue it does just the opposite in your case. – Alex Apr 06 '11 at 19:52

3 Answers3

2

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?"

Jacob
  • 77,566
  • 24
  • 149
  • 228
  • It started as experiment with operator overloading in mind. Changed the fiddle title now. Furthermore, it's all just for fun, but you never know if there will be some use for it in the future. In our country `['%+']` could be used to calculate an amount with VAT include for example. On the other hand: `Number.prototype.VAT` or something like that could do the same. – KooiInc Apr 06 '11 at 19:56
1

I can't see how that would affect anything. Looks like the only way would be by a typo where before it notify the developer that there is no such operator (I'm assuming) but now it will let you do it. Though I'm not an experienced javascript developer.

Brian T Hannan
  • 3,925
  • 18
  • 56
  • 96
1
alert( 'hello '['+']('world ','and ','see you later!') );

Yes, there's a side effect to doing stuff like this - it makes your code unreadable. What the hell were you smoking when you came up with this scheme?

Also, what you're doing has nothing to do with operators. You're just creating an object property whose name happens to be "+" or "+++". A "+" character is only an operator if the interpreter considers it to be an operator. If it's inside a string literal, then it's just another character.

Mike Baranczak
  • 8,291
  • 8
  • 47
  • 71
  • Actually I gave up smoking 9 weeks ago. That must be it! ;D – KooiInc Apr 06 '11 at 20:14
  • Anyway, yes, that's a genuine side effect. And yes, it's not operators, I'm aware of that. That's why we can't use `Number.prototype.+++` Let's call it 'operator-like' or something. – KooiInc Apr 06 '11 at 20:20
  • Mmm, what to make of this btw? http://www.indiscripts.com/post/2010/05/operator-overloading-with-extendscript – KooiInc Apr 07 '11 at 13:47