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

 ̄綄美尐妖づ 提交于 2020-01-06 15:26:09

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/3757269/how-to-set-object-property-in-prototype-function-scope-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!