返回
this的再度认识
前端
2023-12-31 22:44:18
this 在 JavaScript 中扮演着重要的角色,它代表着当前执行代码的对象。本文将重新认识 this,从默认绑定、隐式绑定到箭头函数的 this,深入理解 this 的用法和注意事项,帮助你更熟练地编写 JavaScript 代码。
默认绑定
在 JavaScript 中,this 的默认绑定规则是:
- 在普通函数中,this 绑定到函数的调用者。
- 在方法中,this 绑定到方法所属的对象。
- 在构造函数中,this 绑定到新创建的对象。
function foo() {
console.log(this); // this 绑定到 window 对象
}
const person = {
name: 'John',
greet() {
console.log(this); // this 绑定到 person 对象
},
};
const obj = new Person('John');
console.log(this); // this 绑定到 obj 对象
隐式绑定
除了默认绑定之外,this 还可以通过隐式绑定来改变指向。隐式绑定有以下两种情况:
- 隐式绑定 1:call() 和 apply() 方法
call() 和 apply() 方法可以显式地绑定 this 指向。call() 方法接受一个参数作为 this 的值,apply() 方法接受一个数组作为 this 的值。
const person = {
name: 'John',
greet() {
console.log(this.name);
},
};
const obj = {
name: 'Jane',
};
person.greet.call(obj); // 输出: "Jane"
person.greet.apply(obj); // 输出: "Jane"
- 隐式绑定 2:箭头函数
箭头函数没有自己的 this,它会继承外层函数的 this。
const person = {
name: 'John',
greet() {
console.log(this.name);
},
};
const arrowGreet = () => {
console.log(this.name);
};
person.greet(); // 输出: "John"
arrowGreet(); // 输出: "undefined"
在严格模式下,箭头函数的 this 总是绑定到 undefined。
箭头函数的 this
箭头函数没有自己的 this,它会继承外层函数的 this。
const person = {
name: 'John',
greet() {
const arrowGreet = () => {
console.log(this.name);
};
arrowGreet();
},
};
person.greet(); // 输出: "John"
在严格模式下,箭头函数的 this 总是绑定到 undefined。
结束
this 在 JavaScript 中扮演着重要的角色,它代表着当前执行代码的对象。默认情况下,this 绑定到函数的调用者。通过隐式绑定,可以改变 this 指向。箭头函数没有自己的 this,它会继承外层函数的 this。在严格模式下,箭头函数的 this 总是绑定到 undefined。