Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript adding methods to String instance

Tags:

javascript

Is it possible to add methods to a String instance, for example

x = "123"
x.method = function() { console.log("test") }

x.method()
like image 796
user2032804 Avatar asked Feb 18 '23 00:02

user2032804


2 Answers

Yes, you can do it. You have to first take the string primitive and make it a string instance, though:

x = new String("123");
x.method = function() { console.log("test") };

x.method();

JavaScript has both string primitives and string instances. In your original code, when you wrote:

x.method = ...;

...the string primitive was retrieved from the variable x and promoted to a string instance, to which you added the method, but since the string instance was never stored back to the x variable, the method wasn't there when you tried to call it. (Yes, this is counter-intuitive.)

By using new String(...) in the above, I actually get the string instance and store it in x. Then, since it's a proper object, I can add properties to it.

You can also add methods to String.prototype, like this:

String.prototype.capitalize = function() {
    return this.substring(0, 1).toUpperCase() + this.substring(1);
};

console.log("testing".capitalize()); // "Testing"

Some feel this is bad practice. Others say it's exactly why we have prototypical inheritance, so we can use the prototype to enhance things. While I've never seen any problem from people enhancing String.prototype, I have seem problems when people enhance Array.prototype (because people insist on misuing for-in) and Object.prototype.

like image 158
T.J. Crowder Avatar answered Feb 19 '23 12:02

T.J. Crowder


Strings and numbers are autoboxed primitives, meaning that when you perform OO operations on them, they are cast as "String" and "Number" classes but then are immediately unboxed.

Your code evaluates to:

x = "123"
(new String(x)).method = function() { console.log("test") }

(new String(x)).method() // Error

Your second call is failing because you are dealing with an entirely different String object. As T.J. stated, you can get around this by making x a String object, but this is not a common or recommended practice.

You can extend all strings by adding the method to String.prototype:

x = "123"
String.prototype.method = function() { console.log("test") }

x.method()

This call evaluates the same way as (new String(x)).method() but since that method exists in the prototype, it will get called.

like image 40
Brian Nickel Avatar answered Feb 19 '23 14:02

Brian Nickel