Question

I'm new to javascript and have a question that's probably stupid.

Context

or is a method that I have written myself for the String class through monkey patching.

Question

I want to be able to call the or method like this:

'dog'.or('cat')

The problem is that the or method needs to know about the string that it was called on.

Is there anyway to access 'dog' from inside the or method without passing it in as a parameter?

Was it helpful?

Solution

You can access it using the this keyword. Read more.

Here is an example:

String.prototype.show = function ()
{
    alert(this);
}
"Hello, World!".show();

See it in action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top