What is the use of call, apply and bind in JavaScript? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What is the use of call, apply and bind in JavaScript?

29th Apr 2018, 1:02 AM
Akhil Kumar Reddy Pasham
Akhil Kumar Reddy Pasham - avatar
3 Answers
29th Apr 2018, 3:11 AM
Sanh-Thanh Ng
Sanh-Thanh Ng - avatar
+ 3
Hi Akhil Bind, Call and Apply are used to attach what "this" property refers to in functions. All JavaScript functions are Objects and come with these 3 methods as standard. However what "this" refers to can be a bit confusing, have a look at my explanation of "this" on this post. https://www.sololearn.com/Discuss/1226611/what-is-the-function-of-this-keyword-in-javascript example of bind: So you have a game where you have defined a number of monsters function monster(name,life){ this.name=name; this.life=life; this.status = function() { return `monster ${this.name} has life ${this.life}`; }; } let monster1=new monster("slime",10); let monster2=new monster("goul",8); console.log (monster1.name); //slime console.log (monster2.name); //goul Now we wish to attach a weapon function to these monsters, so rather than define lots of functions for each monster we just need to define a single function like this. function weapon(s,w) { return `${this.name} strikes you with ${s} ${w}`; } Now we can use bind to attach this weapon function to our monsters, passing parameters for that particular monster. var strike1 = weapon.bind(monster1,"big","sword"); var strike2 = weapon.bind(monster2,"small","laser"); console.log (strike1()); //slime strikes you with big sword console.log (strike2()); //goul strikes you with small laser bind creates a new instance of the weapon function each time it is called, and so can use the variables in that particular monster. call is the same, but it is used if just want to call that function once, and execute it straight away. console.log(weapon.call(monster1,"small","stick")); //slime strikes you with small stick apply is the same as call, except you pass in parameters as an array console.log(weapon.apply(monster1,["big","stick"])); //slime strikes you with big stick There many other uses for these three methods for functions, but above is a good start to try and understand.
29th Apr 2018, 3:56 PM
Mike Choy
Mike Choy - avatar
0
Thank you! Thanh.
29th Apr 2018, 4:05 AM
Akhil Kumar Reddy Pasham
Akhil Kumar Reddy Pasham - avatar