-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()
matisetorm
  • 857
  • 8
  • 21
henrybbosa
  • 1,139
  • 13
  • 28

1 Answers1

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());
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • please give a small example – henrybbosa Oct 11 '17 at 07:17
  • @henrybbosa See it – Suren Srapyan Oct 11 '17 at 07:18
  • Please don't answer obvious duplicates like these. Close them as a duplicate instead Answering them disqualifies the (closed) duplicate from being [automatically deleted](https://stackoverflow.com/help/roomba), and the answer only serves to further divide where information can be found. – Cerbrus Oct 11 '17 at 07:26