Javascript Call and Apply functions1 min read

WHAT?
What are Call and Apply functions?
Call and Apply functions are predefined Javascript functions which are used to bind object passed into function.
In other words with Call or Apply we invoke a function with an owner object as the first parameter.
HOW?
i.e.:
let car = { model: 'BMW', year: '2009' } let car2 = { model: 'MERCEDES', year: '2017' } function printCarProps(msg) { console.log(`${msg}` ${this.model} ${this.year}); } printCarProps.call(car,"Best car is:"); // outputs: Best car is BMW 2009 printCarProps.call(car2,"Only"); // outputs: Only MERCEDES 2017
Apply function does the same thing as Call but the only difference is the way in which each of these functions accepts arguments.
Apply accepts it as an array:
i.e.:
printCarProps.apply(car,[msg]);
Call accepts it as subsequent parameters:
i.e.:
printCarProps.call(car,msg);
SUMMARY:
Call and Apply both are used to force the this value when a function is executed but the difference is in passing arguments.

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Did you stumble upon a…

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Little chit-chat Hi! Let me…