Chirag Kothari Chirag Kothari - 4 months ago 9
Javascript Question

How to change the context of function using 'bind'?

function greet(){
return 'Hi ' + this.name;
}
greet = greet.bind({name: 'Tom'});
greet(); // Hi Tom
greet = greet.bind({name: 'Harry'});
greet(); // Hi Tom (Why??)


'bind' should return a new function with new values for 'this'. Why is this not working?

Answer

Once a function is binded to a custom object, it cannot be changed. This is what you can do where the original function is unchanged:

function greet(){
  return 'Hi ' + this.name;
}
greet1 = greet.bind({name: 'Tom'});
greet1(); // Hi Tom
greet1 = greet.bind({name: 'Harry'});
greet1(); // Hi Harry