0

I am trying to extend a method to the String prototype.

I want this method to manipulate the string value but I am not sure how do access it.

this the current object context seems to refer to the string object, but not the actual string value.

String.prototype.test = function() { console.log(this)}
function () { console.log(this) }
'lol'.test()
 VM192:2 String {0: "l", 1: "o", 2: "l", length: 3, 
 has: function, contains: function, 
 escapeRegExp: function, camelize: function…
}

How do I access the string value instead of the string object?

1
  • The string object is the string, for all practical purposes. What you are seeing in the console is an artifact of some internal machinery combined with how console.log works. In all other contexts, the string object is essentially identical to its primitive value. In this case, in addition to using toString() as suggested in the answers, you can also say this+"" or this.valueOf(). Commented Jan 6, 2015 at 11:56

2 Answers 2

5

You need call toString()

String.prototype.test = function() { 
    console.log(this.toString())
}
Sign up to request clarification or add additional context in comments.

Comments

3

Just call toString method:

console.log( this.toString() )

Comments

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.