1

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

2 Answers 2

6

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 () { ... };
Sign up to request clarification or add additional context in comments.

6 Comments

It should probably just be var foo = "Bar"
Ah I see. Carry on then.
That's why I said "You'll need to make it a String object rather than a primitive though."
But of course using a string object may introduce other problems.
@Khalid not always - it will be called automatically in some cases. You really have no other choice than something like this.
|
0

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.

2 Comments

You wouldn't be able to call the function though. Primitives don't have properties. What happens behind the scene is that JS converts the primitive to an object, but discards the object again.
I tried it before but didn't work. TypeError: undefined is not a function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.