Say I define a class Template()
within which I need to extend String
with some prototype
to add functionalities to it:
function Template() {
String.prototype.replaceAll = function(find, replace) {
return this.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
}
this.test = function (){
return "hello".replaceAll("h", "y");
}
}
Now if I declare a new Template()
, the String.prototype
is public:
var myTemplate = new Template();
console.log(myTemplate.test()); // outputs "yello", this is desired
console.log("hello".replaceAll("h", "y")); // outputs "yello", this should not work
Whereas what I would want is for String
to go unchanged outside of the Template()
class while still being extended from within.
How do you declare a private prototype from within a class in javascript?