【问题标题】:private prototype from within a class类中的私有原型
【发布时间】: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

而我希望 StringTemplate() 类之外保持不变,同时仍从内部扩展。

如何在 javascript 的类中声明私有原型?

【问题讨论】:

  • 你没有。类型的原型是全局的(或者,至少与类型本身一样全局)。
  • javascript 中没有“私有”之类的东西。

标签: javascript prototype private


【解决方案1】:

一般中,你会做相反的事情;您创建一个新函数,其原型是您要扩展的“类”,然后将新方法添加到该函数;

function MyString() {

}

MyString.prototype = new String();
MyString.prototype.replaceAll = function (find, replace) {
    return this.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
};

...您可以在任何范围内创建MyString,以便它是您想要的私有或公共。然后,在您的范围内创建MyString 而不是String 的实例。这为您提供了所需的额外(“私有”)原型。

然而,字符串是一个基元,基元不像普通对象那样工作;具体来说,they are autoboxed/ upcast to objects when you call methods on them。这将意味着上述内容不适用于您的情况;因为"abc".replaceAll() 将始终自动装箱到String,而不是MyString;而且你不能告诉 JavaScript 做其他事情。

相反,你应该做的是(因为你不应该修改你不拥有的东西),是创建一个您将字符串传递到其中以完成脏活的辅助函数;

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
}

【讨论】:

    【解决方案2】:

    这是不可能的,因为String 是一个全局对象。无论你在哪里更改它或它的原型,它都会受到影响。

    在你的情况下,你应该在你的类中声明一个辅助函数。

    function Template() {
    
        function stringReplaceAll(str, search, replace) {}
    
    }
    

    此课程仅在您的班级中可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2013-08-02
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多