Javascript adding methods to String instance

javascript

Solution

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.

Problem

Is it possible to add methods to a `String` instance, for example ``` x = "123" x.method = function() { console.log("test") } x.method() ```

Original source

Related problems