var car ={registrationNumber:"FT5142",brand:"Benz",}functiondisplayDetails(ownerName){console.log(ownerName +", this is your car: "+this.registrationNumber+" "+this.brand);}// car.displayDetails();
displayDetails.apply( car,["Raymund"]);
displayDetails.call(car,"Raymund");
* call apply and bind
-This concept is called function borrowing
-We can borrow functionfrom the other objects
and use the data with the other object.->Call invokes the function and allows you to pass in arguments
one by one.->Apply invokes the function and allows you to pass in arguments
as an array.->Bind returns a newfunction, allowing you to pass in a
this array and any number of arguments.let myName ={firstname:"Abhishek",lastname:"Bhavsar",}letprintFullName=function(hometown, state){console.log("=>>>>>>>",this.firstname+" "+this.lastname+"from"+ hometown +","+ state)}// call
printFullName.call(myName,"Ahmedabad","Gujrat");let name2 ={firstname:"Sachin",lastname:"Tendulkar",}// function borrowing
printFullName.call(name2,"Mumbai","Maharashtra");// apply
printFullName.apply(name2,["Mumbai","Maharashtra"]);// bind methodlet printMyName = printFullName.bind(name2,"Mumbai","Maharashtra");console.log(printMyName);printMyName();
// ----------------------// Traditional Example// ----------------------// A simplistic object with its very own "this".var obj ={num:100}// Setting "num" on window to show how it is NOT used.window.num=2020;// yikes!// A simple traditional function to operate on "this"varadd=function(a, b, c){returnthis.num+ a + b + c;}// callvar result = add.call(obj,1,2,3)// establishing the scope as "obj"console.log(result)// result 106// applyconst arr =[1,2,3]var result = add.apply(obj, arr)// establishing the scope as "obj"console.log(result)// result 106// bindvar result = add.bind(obj)// establishing the scope as "obj"console.log(result(1,2,3))// result 106