What is Javascript Call Apply ?

Javascript Call Apply :
Assume this is the code

function Person(firstName) {
  this.firstName = firstName;
}
Person.prototype.sayHello = function() {
  alert("Hello, I'm " + this.firstName);
};

sayhello is a prototype method for person

var person1 = new Person("Alice");

now consider this

person1.sayHello()

i am inheriting the person so it will print

Hello I’m Alice

alert("Hello, I'm " + this.firstName);

In this situation “this” means the person1 object that is why it was able to find firstName which is a property of Person object but now see this

var helloFunction =person1.sayHello;

Here im assigning the reference of sayhello function to another variable which is not related to person in anyway but still it can be executed like this

helloFunction();

But now the function is not being executed under person object context but under window context which is global

window.sayHello();

so it will try to find a field called first name in window object which will be undefined.

Now i want to pass reference to this function but i still want the reference to find the first name like the first case.In first case this was person1.In second case i executed with ‘this’ as window so if i want to give an inner function as reference to some other object and want to give him access to my object variables when he executes the function reference then i do this

hellofunction.apply(person1);

In this case im executing the outside reference but i tell javascript that i want the ‘this’ to be person1 instead of window so if i do this i will get

Hello Im Alice

call and apply do same thing: only difference is in how you pass arguments to the function in above equation, if sayhello was declared with an argument

person1.sayHello('Somevalue);

This is the first case if you want to do it with call then

helloFunction.call(person1,'Somevalue')

but in apply you pass the arguments as an array

helloFunction.apply(person1,['SomeValue]);

So if you have varying arguments for the function people usually use apply but if the number of arguments is less then,people use call,but both give u same output.

Trick To Remember: The apply function allow us to execute a function with an array of arguments of parameters,Call accepts an argument list.

About

My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Javascript Tagged with: