一、认识this
在 JavaScript 中,关键字 this 是一个特殊的对象,它在函数执行时绑定,并且根据函数的调用方式和上下文不同而具有不同的值
二、this指向对象
1.全局上下文:在全局作用域中,函数直接被调用时,this 指向全局对象(在浏览器中是 window 对象,在 Node.js 中是 global 对象)。
console.log(this); // 在全局作用域中输出全局对象(window 或 global)
2.函数上下文:当函数作为对象的方法被调用时,this 指向调用该方法的对象。
const obj = {
name: 'John',
sayHello: function() {
console.log('Hello, ' + this.name);
}
};
obj.sayHello(); // 输出 "Hello, John"
3.构造函数上下文:当函数作为构造函数使用 new 关键字创建对象时,this 指向新创建的实例对象。
function Person(name) {
this.name = name;
}
const john = new Person('John');
console.log(john.name); // 输出 "John"
4.箭头函数:箭头函数没有自己的 this 绑定,其会绑定上层作用域的this。(对象没有this,只有函数才有this)
const obj = {
name: 'John',
sayHello: function() {
setTimeout(() => {
console.log('Hello, ' + this.name);
}, 1000);
}
};
obj.sayHello(); // 输出 "Hello, John"(箭头函数捕获了 obj 的 this 值)
三、使this指向改变的三种方法
1.call()
const obj = {
name: 'John',
sayHello: function() {
setTimeout(() => {
console.log('Hello, ' + this.name);
}, 1000);
}
};
obj.sayHello(); // 输出 "Hello, John"(箭头函数捕获了 obj 的 this 值)