Chirag Kothari Chirag Kothari - 1 year ago 64
Javascript Question

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

function greet(){
return 'Hi ' +;
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 Source

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 ' +;
greet1 = greet.bind({name: 'Tom'});
greet1(); // Hi Tom
greet1 = greet.bind({name: 'Harry'});
greet1(); // Hi Harry
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download