Saturday, 13 May 2017

please explain the apply and call methods in javascript










What is the main difference between apply and call methods...
I go through the web but unable to find the best solution..
Please help me friends...



Answer



Every function in JavaScript receives two objects in addition to the default parameters. These are this and arguments. The value of this is determined by it's invocation pattern. apply or call can be used to invoke a function and provide it a default this object.



This will be very useful in many situations. For example, arguments is an array-like object, but not really an Array with all the useful Array methods. So, to apply an Array method slice on arguments, you can do this:



Array.prototype.slice.apply(arguments, [1, 2])


Had arguments been an object of Array type, you could have used




arguments.slice(1, 2) 


call is nothing but a modified version of apply. See elusive's comment.



Mr.Douglus Crockford gives a very good introduction to JavaScript functions in this video: Function the Ultimate.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...