Khalid
Khalid

Reputation: 4808

How to add function to specific string in javascript

I have a string in 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

Upvotes: 1

Views: 82

Answers (2)

Ali Motevallian
Ali Motevallian

Reputation: 1380

If you want it to work only on your variable Foo then simply do the following:

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

You don't need to add the function to the prototype of String.

Upvotes: 0

Quentin
Quentin

Reputation: 943643

So apply it only to the string in the variable Foo.

You'll need to make it a String object rather than a primitive though.

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

Upvotes: 6

Related Questions