2

I am kinda new to js and would appreciate some help to clarify one subject. Basically i want to call some functions that i write like default javascript are called:

//declaring function
const splitAsExample = text => text.split('|')

//calling function
splitAsExample('Yesterday|Today|Tomorrow')

Instead of calling the function as mentioned above, i would like to know if it's possible to make a function that can be called like:

'Yesterday|Today|Tomorrow'.splitAsExample()

//and || or
'Yesterday|Today|Tomorrow'.splitAsExample

I learned js all by myself and didn't manage to find a specific name for this question to search up in google. :) If you can clarify this topic for me it would be great, but if you could give me the name to search it up would be even better!

2
  • Add it to the prototype of String String.prototype.splitAsExample Commented Aug 31, 2020 at 10:56
  • 1
    'Yesterday|Today|Tomorrow'.splitAsExample() would be possible but you would have to mess with the prototype of the builtin String object: How does JavaScript .prototype work? Commented Aug 31, 2020 at 10:57

1 Answer 1

2

You could add a prototype function to String.

This allows method chaining with a given object.

String.prototype.splitAsExample = function () { return this.split('|'); };

console.log('Yesterday|Today|Tomorrow'.splitAsExample());

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

1 Comment

"You could..." - But there's almost always a better way instead of modifying the prototype of a builtin object like String

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.