0

I'm trying to learn how to add new methods in the String.prototype in JavaScript. But I can't figure out a way on how to access the string specified in the new method:

String.prototype.new_method = function(){ THE_STRING; };

So that it will return "abc" when I call it:

"abc".new_method();

I know this can easily be done by doing:

function returnstring(str){
   return str;
}

But I really want to learn how prototypes in JavaScript works.

2 Answers 2

3

Use 'this' to access the string:

String.prototype.new_method = function(){ alert(this); };
"abc123".new_method();

Sign up to request clarification or add additional context in comments.

Comments

0

You can access the string with this.

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.