如何使用'bind'更改函数的上下文?

时间:2016-07-28 12:18:54

标签: javascript

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

'bind'应返回一个带有'this'新值的新函数。为什么这不起作用?

1 个答案:

答案 0 :(得分:1)

将函数绑定到自定义对象后,无法更改。这是原始函数不变的原因:

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