Call(), apply() and bind() methods in JavaScript
Call()
Call means the function are borrowing to another function. or the function worked on different objects.
In this example, we console 'this', so 'this' refers to whole object.const obj1 = {name : 'shreyash',age : 20,details : function(){console.log(this)}}obj1.details()
Supposed we want to access name so we can easily do it using this keyword "this.name"
supposed have a two object and we need to used inside obj1 function in obj2 ...it is possible?const obj1 = {name : 'shreyash',age : 20,details : function(){console.log(`Name : ${this.name}, Age: ${this.age}`)}}obj1.details()
Yes it is possible using call () method
apply method is similar to the call method only difference is call method pass argument individually and apply method need to pass the argument in the form of list.
Bind()const arr = ["shreyash", "omkar", "kiran"];userObj.printInfo.bind(user2, arr);
Bind method is different from call and apply method. we can directly execute the call and apply method but in the case of Bind() see this fig. it return hole function without execute. this is the power of bind method.
Post a Comment