Search code examples
javascriptscopeecmascript-6prototype-programming

Functions attached to string prototypes within scope only


It is very simple to add methods to classes such as String prototypically. However, this affects all strings in the global scope.

How can I add a method accessible from all string literals like such: "foo".bar(), such that that method is only accessible within the scope of an ES6 class, say, or a function call?


Solution

  • I am afraid that you may not be able to do that. Also it seems like it's a bad idea. It will be probably better if you just use normal function. Like: bar("foo")