简体   繁体   English

如何在JavaScript中向特定字符串添加函数

[英]How to add function to specific string in javascript

I have a string in javascript 我在javascript中有一个字符串

var Foo = "Bar";

I have a function that does a manipulation on this string. 我有一个函数对此字符串进行操作。 to add this function to the string I did this 将此功能添加到字符串中

String.prototype.func = function(){
   // code
}

But this function will work for every string. 但是此函数将适用于每个字符串。 I want this function to be called only from my variable Foo 我希望仅从变量Foo调用此函数

So apply it only to the string in the variable Foo . 因此,仅将其应用于变量Foo的字符串。

You'll need to make it a String object rather than a primitive though. 不过,您需要将其设置为String对象,而不是原始类型。

var foo = new String("Bar");
foo.func = function () { ... };

If you want it to work only on your variable Foo then simply do the following: 如果您希望它仅对变量Foo起作用,则只需执行以下操作:

var Foo = new String("Bar");
Foo.func = function(){
    //code
};

You don't need to add the function to the prototype of String. 您不需要将函数添加到String的原型中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM