🎓 作者简介: 前端领域优质创作者
🚪 资源导航: 传送门=>
🎬 个人主页: 江城开朗的豌豆
🌐 个人网站: 江城开朗的豌豆 🌍
📧 个人邮箱: YANG_TAO_WEB@163.com 📩
💬 个人微信: y_t_t_t_ 📱
📌 座 右 铭: 生活就像心电图,一帆风顺就证明你挂了。 💔
👥 QQ群: 906392632 (前端技术交流群) 💬
大家好,我是[小杨],今天我们来聊聊JavaScript中让人又爱又恨的this
关键字。很多初学者对this
的指向感到困惑,其实只要掌握规律,this
并没有那么神秘。更重要的是,我们还可以用3种方法来改变this
的指向!
1. this
到底是什么?
简单来说,this
指向当前执行代码的环境对象,但它会根据调用方式动态变化。来看几个常见场景:
1.1 全局环境下的this
console.log(this); // 浏览器中指向window,Node.js中指向global
1.2 函数中的this
function sayHello() {
console.log(this); // 严格模式下是undefined,非严格模式指向window
}
sayHello();
1.3 对象方法中的this
const person = {
name: "我",
greet() {
console.log(`你好,我是${this.name}`); // 指向person对象
}
};
person.greet(); // 输出:"你好,我是我"
1.4 构造函数中的this
function Person(name) {
this.name = name;
}
const me = new Person("我");
console.log(me.name); // "我"
2. 3种方法改变this
指向
有时候我们希望this
指向特定的对象,这时候就需要手动改变它的指向。JavaScript提供了3种方法:
2.1 call()
- 立即调用,显式绑定this
function introduce(language) {
console.log(`我是${this.name},我会${language}`);
}
const person1 = { name: "我" };
const person2 = { name: "你" };
introduce.call(person1, "JavaScript"); // 我是我,我会JavaScript
introduce.call(person2, "Python"); // 我是你,我会Python
2.2 apply()
- 类似call()
,但参数是数组
function showSkills(skill1, skill2) {
console.log(`${this.name}的技能:${skill1}、${skill2}`);
}
const me = { name: "我" };
showSkills.apply(me, ["编程", "设计"]); // 我的技能:编程、设计
2.3 bind()
- 返回一个新函数,永久绑定this
const person = {
name: "我",
sayName: function() {
console.log(this.name);
}
};
const sayMyName = person.sayName.bind(person);
setTimeout(sayMyName, 100); // 1秒后输出"我"
3. 箭头函数的this
特殊之处
箭头函数没有自己的this
,它会继承外层作用域的this
:
const obj = {
name: "我",
regularFunc: function() {
console.log(this.name); // "我"
},
arrowFunc: () => {
console.log(this.name); // undefined(取决于外层this)
}
};
obj.regularFunc();
obj.arrowFunc();
4. 实际应用场景
4.1 解决回调函数this
丢失问题
class Counter {
constructor() {
this.count = 0;
// 使用bind固定this指向
this.increment = this.increment.bind(this);
}
increment() {
this.count++;
console.log(`当前计数:${this.count}`);
}
}
const counter = new Counter();
document.querySelector('button').addEventListener('click', counter.increment);
4.2 借用其他对象的方法
const car = {
brand: "Toyota",
getBrand: function() {
return this.brand;
}
};
const bike = {
brand: "Giant"
};
console.log(car.getBrand.call(bike)); // "Giant"
5. 总结
-
this
的指向由调用方式决定 -
三种改变
this
的方法:call(thisArg, arg1, arg2...)
apply(thisArg, [argsArray])
bind(thisArg)
-
箭头函数没有自己的
this
,会继承外层this
记住这些规则,this
就不再是难题了!如果有任何疑问,欢迎在评论区讨论~