-2

I need to write a method I will call on a string literal in JavaScript. A method that I want to call:

"Javascript".toKampala();

Does that feature exist in JavaScript? and if it does How do I write such a method (toKampala()) on a JavaScript literal or any object?

In Kotlin I did it like this;

fun String.toHenry():String{
    return "$this Henry";
}

and I can call

"chalres".toHenry()
9
  • Henry, please do some research before asking a question on Stack Overflow. By searching for your question's title in google, I the answer could be found in the first search result. Commented Oct 11, 2017 at 7:20
  • I did But maybe I was using the same word like in the heading Commented Oct 11, 2017 at 7:22
  • Good I got the answer here Thanks Commented Oct 11, 2017 at 7:22
  • I literally copy-pasted "How to write Extensible methods in javacript" into google to find these 2 dupe targets... Commented Oct 11, 2017 at 7:23
  • I actullay wanted to know if that method workes on all javascript objects Commented Oct 11, 2017 at 7:24

1 Answer 1

1

Every string is default has a prototype, which is the String.prototype object and it can access anything which are defined there.

You need add that method in the String.prototype and it will be accessible from any string. You can access the current string in that function by this.

String.prototype.toHenry = function() {
  return this + ' Hentry';
};

console.log('charles'.toHenry());

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

3 Comments

please give a small example
@henrybbosa See it
Please don't answer obvious duplicates like these. Close them as a duplicate instead Answering them disqualifies the (closed) duplicate from being automatically deleted, and the answer only serves to further divide where information can be found.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.