【发布时间】:2014-09-09 15:39:08
【问题描述】:
假设我定义了一个类 Template(),我需要在其中扩展 String 并使用一些 prototype 来为其添加功能:
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");
}
}
现在,如果我声明 new Template(),String.prototype 是公开的:
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
而我希望 String 在 Template() 类之外保持不变,同时仍从内部扩展。
如何在 javascript 的类中声明私有原型?
【问题讨论】:
-
你没有。类型的原型是全局的(或者,至少与类型本身一样全局)。
-
javascript 中没有“私有”之类的东西。
标签: javascript prototype private