Search code examples
javascriptprototypescopethis

How to set object property in prototype function (scope problem)?


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.


Solution

  • 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