返回
最全this使用说明,别再分不清了!
前端
2024-01-11 19:31:13
什么是this
this是一个,它的指向在不同情况下是不同的。在JavaScript中,函数的作用域决定了this的指向。函数可以是全局函数、对象方法、构造函数或者箭头函数,this的指向也会根据函数的不同类型而有所不同。
this的绑定规则
- 默认绑定: 如果函数不是作为某个对象的方法被调用,那么this将指向window对象。
- 隐式绑定: 如果函数作为某个对象的方法被调用,那么this将指向调用它的对象。
- 显式绑定: 通过call()、apply()、bind()方法可以显式地绑定this的指向。
- 箭头函数: 箭头函数没有自己的this,它继承了其外层函数的this指向。
this的指向示例
1. 默认绑定
function sayHello() {
console.log(this); // 输出:window对象
}
sayHello(); // 调用函数
在这个示例中,sayHello()函数不是作为某个对象的方法被调用,因此this指向window对象。
2. 隐式绑定
const person = {
name: "John",
sayHello: function() {
console.log(this.name); // 输出:"John"
}
};
person.sayHello(); // 调用方法
在这个示例中,sayHello()函数作为person对象的方法被调用,因此this指向person对象。
3. 显式绑定
const person = {
name: "John",
sayHello: function() {
console.log(this.name); // 输出:"John"
}
};
const anotherPerson = {
name: "Mary"
};
person.sayHello.call(anotherPerson); // 显式绑定this指向anotherPerson对象
在这个示例中,我们使用了call()方法显式地绑定this指向anotherPerson对象,因此sayHello()函数被调用时,this指向anotherPerson对象。
4. 箭头函数
const person = {
name: "John",
sayHello: () => {
console.log(this.name); // 输出:undefined
}
};
person.sayHello(); // 调用方法
在这个示例中,sayHello()函数是一个箭头函数,它没有自己的this,因此this指向其外层函数(person对象的方法)的this,由于person对象没有name属性,因此输出undefined。
箭头函数中的this
箭头函数没有自己的this,它继承了其外层函数的this指向。这意味着箭头函数中的this与外层函数中的this指向相同。
const person = {
name: "John",
sayHello: function() {
const arrowFunction = () => {
console.log(this.name); // 输出:"John"
};
arrowFunction(); // 调用箭头函数
}
};
person.sayHello(); // 调用方法
在这个示例中,arrowFunction()箭头函数继承了其外层函数sayHello()的this指向,因此this指向person对象。
总结
this的指向在JavaScript中是一个复杂的概念,但只要理解了它的绑定规则,你就可以正确地使用this。总之,this的指向取决于函数的调用方式和类型,以及函数的嵌套层次。