A function can have its own methods - strange but true. Why? Because everything in Javascript is an object and object can have methods.
Consider -
|
|
The first call to getSum
is as expected. The second call uses a method called call
and passes this
as the argument along with the two numbers. This is equivalent to the first call.
Or, use call
's friend apply
-
|
|
Everything stays the same except that the params are sent in an array.
The above example may not seem that useful. Let’s see a marginally better example.
|
|
We are calling a function of an object to get and print color
- nothing amazing.
We will create another object but leave out the function-
|
|
We cannot obviously call getColor
from apple
.
|
|
But, an amazing thing happens when we do this -
|
|
This call invokes fruit
's function in apple
context. So, just like that we are reusing functions across objects that are not related, but just had common props.
The use of such methods may seem bewildering at first - but you had been doing it all along. How do you think methods work as expected across objects & arrays, arrays & strings, and so on?