Javascript provide three ways of a calling a function
- The simple way,
Suppose you have a function
function foo() {
}
and you simply call it with parenthesis like foo()
- By using
call
method of Function.prototype
All right, consider the foo
function again
But this time you need to see it in a different way, every function in javascript is also an object and every object has a prototype which can then have more functions and properties. So when you define a function like that foo
it also becomes an object of Function
and gives you two additional methods to call the function, one of them is call
which expects first argument to be the context or this
and then comma separated list of arguments which you want to pass to function. For example, you have a user object which have properties firstName
and lastName
and you want to have function which will say something to that user, you can define the function like this
function saySomething(something) {
return "Hey " + this.firstName + " " + this.lastName} + " I wanted to say " + something
}
- By using
apply
method of Function.prototype
Very much similar to call
except instead of giving comma separated args you will pass an array.
More on this here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function