Here the object will become this when the function is invoked
function greet(lastName) { console.log(this.firstName + ' ' + lastName);}greet.call({ firstName: "John" }, "Doe"); // John Doegreet.apply({ firstName: "Jane" }, ["Doe"]); // Jane Doe
bind
It binds the this object and return another function
It doesn’t modify the original function
function greet(lastName) { console.log(this.firstName + ' ' + lastName);}let bindedGreet = greet.bind({ firstName: 'John' }, "Doe");bindedGreet(); // John Doe//////////////////////////////////////////////////////////var obj2 = { name: 'LL'}var testFun = (function() { console.log(this.name);}).bind(obj2);var obj = { name: 'KK', test: testFun};// testFun is pre-binded and hence does not print KKobj.test(); // LL
Useful Example:
var clickHandler = { message: 'click event handler', handleClick: function(event) { console.log(this.message); }};var btn = document.getElementById('myBtn');// Add click event to btnbtn.addEventListener('click', clickHandler.handleClick);// Button click causes "undefined" to be printed// Using bind to fix the codebtn.addEventListener('click', clickHandler.handleClick.bind(clickHandler));// Button click causes "click event handler" to be printed
With Arguments
The extra parameters in bind prepends as arguments when we call the function