在不创建原型的情况下创建字符串方法

Creating method for string without creating prototype

我想创建一个方法,您可以像 'string'.doSth() 这样调用,而无需创建新的字符串原型。我该怎么做?

您总是可以扩充 String 的原型。方法如下

   String.prototype.doSomething = function () {
     console.log('doing something');
   }

   var a = 'str';
   a.doSomething();

通过编写 'string',您基本上是在创建一个新的字符串对象。
如果向字符串原型添加 doSth 方法,它将是可调用的:

String.prototype.doSth = function doSth() {
  console.log('Inside');
}
"string".doSth(); // will log 'Inside'

我注意到你不想要 String.prototype

通过执行以下操作避免使用它:

window.doSth = function (s) {
    return s + '!';
};

或者,您可以创建自己的构造函数:

var SpecialString = function (s) {
    this.value = s;
    this.doSth = function () {
        return this.value + '!';
    };
};

现在:

var myString = new SpecialString('Foo');
myString.value; // Its value, Foo
myString.doSth(); // Returns Foo!

剩下的留给你,以防你改变主意

thisString.prototype

您可以使用 String.prototype。这会让你 "add functions" 串起来。要获取字符串,请使用 this:

String.prototype.doSth = function () {
    alert(this);
};

var testString = 'Foo Bar';
testString.doSth(); // Alerts "Foo Bar"


使用return

使用return产生一个新值。假设您希望此函数在字符串末尾添加感叹号 !

String.prototype.addExclamation = function () {
    return this + '!';
};

现在:

var testString = "Foo";
var newString = testString.addExclamation();
alert(newString); // Alerts Foo!


唯一的其他方法是不创建全局函数并将其添加到 String

String.doSth = function(str) {
  //do something
}
String.doSth('hi');