views:

31

answers:

1

This is something trivial, which I've forgotten. There are possibly duplicates - I searched a little, found similar, but couldn't find as concise.

   String.prototype.test = function(){this.bar = this.length + 2;}

   var str = "foo";
   str.test();

   console.log(str);                         // foo
   console.log(str.bar);                     // undefined

Pretty sure it has to do with this being trapped in the closure.

A: 

Has to do with the way you're creating your string in this case. Try:

var str = new String("Foo");

and you'll find it magically working. :-]

See an example at: http://jsbin.com/odozo3/edit

Erik
I found this right before you answered that. :) kudos to us
vol7ron
I vaguely remember that the `new` keyword is needed for prototype methods. Any ideas on how to get it working without specifying the object type (eg with just `var str = "foo";`)?
vol7ron
Simple answer @vol7ron: You can't.
Erik
Yeah, I vaguely remember that too. There are workarounds, but w/o any extra code there's no way to do it without late binding.
vol7ron