this.fn=this.fn.bind(this)详细解释一下原理
时间: 2023-09-30 11:05:25 浏览: 46
`this.fn=this.fn.bind(this)` 是用于绑定函数中 `this` 的值的语法。具体来说,它会将函数中的 `this` 值绑定为当前函数对象所在的上下文(也就是该函数被调用时所处的对象或者环境)。
在 JavaScript 中,函数的 `this` 值默认指向全局对象(在浏览器中,通常是 `window` 对象)。但是在函数调用时,`this` 值实际上是由调用方式决定的。例如:
```javascript
const person = {
name: 'Alice',
sayHi() {
console.log(`Hi, my name is ${this.name}`);
}
};
person.sayHi(); // 输出 "Hi, my name is Alice"
const hello = person.sayHi;
hello(); // 输出 "Hi, my name is undefined"
```
在上面的例子中,`person.sayHi()` 方法的 `this` 值指向了 `person` 对象,因此输出了正确的结果;而 `hello()` 方法是直接调用了 `sayHi` 函数本身,此时 `this` 值指向了全局对象,因此输出了 `undefined`。
为了解决这个问题,我们可以使用 `bind` 方法来将函数绑定到一个特定的 `this` 值上,例如:
```javascript
const hello = person.sayHi.bind(person);
hello(); // 输出 "Hi, my name is Alice"
```
在上面的例子中,`bind` 方法返回了一个新的函数,该函数的 `this` 值永远绑定为 `person` 对象。因此,无论如何调用 `hello` 函数,它的 `this` 值都会指向 `person` 对象。
因此,`this.fn=this.fn.bind(this)` 的作用是将当前函数对象的 `this` 值绑定为当前函数对象所处的上下文(通常是调用该函数的对象或者环境),从而确保在函数调用时,`this` 值不会出错。