【问题标题】:Functions attached to string prototypes within scope only仅在范围内附加到字​​符串原型的函数
【发布时间】:2017-01-19 22:22:55
【问题描述】:

String 等原型中添加方法非常简单。但是,这会影响全局范围内的所有字符串。

如何添加一个可从所有字符串字面量访问的方法,例如:"foo".bar(),这样该方法只能在 ES6 类或函数调用的范围内访问?

【问题讨论】:

    标签: javascript scope ecmascript-6 prototype-programming


    【解决方案1】:

    恐怕你做不到。此外,这似乎是一个坏主意。 如果您只使用普通功能可能会更好。点赞:bar("foo")

    【讨论】:

      【解决方案2】:

      这是不可能的。字符串是原语。当像对象一样使用它们时,它们被强制转换为 String 实例(因此可以使用 String.prototype 方法)。此行为不依赖于范围。

      对于

      class Superstring extends String {
        bar() {
          return `${this} bar`;
        }
      }
      

      可以

      new Superstring('foo').bar();
      

      const bar = (str) => Superstring.prototype.bar.call(str);
      
      bar('foo');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-29
        • 2012-11-16
        • 2014-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多