React 事件绑定/this绑定的几种方式
· 阅读需 4 分钟
MDN中 Function.prototype.bind()
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
先引入一个例子:
const module = {
x: 42,
getX: function() {
return this.x;
}
};
let unboundGetX = module.getX;
console.log(unboundGetX()); // 该函数在全局范围内被调用
// 输出: undefined
unboundGetX = unboundGetX.bind(module);
console.log(unboundGetX());
// 输出: 42