关于普通函数和箭头函数的this
2026年5月4日 14:19
箭头函数的作用以及函数的二义性
函数的两种作用
- 作为指令序列,直接调用
- 作为构造函数,使用new关键字创建实例对象
JS中的this
- this作为全局上下位的一部分,仅在函数被调用时才创建
// ❌ 错误理解sadasda'张三',
this: '???', // 这只是一个普通属性,不是 this
thisValue: this // 这里的 this 是全局对象,不是 obj
};
// ✅ 正确理解:this 是在函数执行时确定的
const obj2 = {
name: '李四',
sayName() {
console.log(this.name); // this 在执行时才绑定到 obj2
}
};
obj2.sayName(); // '李四' - this 指向 obj2
- 普通函数this的绑定时机:普通函数定义时 this 未绑定
function showThis() {
console.log(this);
}
const obj1 = { name: 'obj1', show: showThis };
const obj2 = { name: 'obj2', show: showThis };
// 同样的函数,不同的调用方式,this 指向不同
obj1.show(); // { name: 'obj1', show: f }
obj2.show(); // { name: 'obj2', show: f }
showThis(); // window/global (严格模式 undefined)
// 证明:函数没有固定的 this
console.log(showThis === obj1.show); // true (同一个函数)
- 箭头函数的this是在定义时决定的,在函数作用域内向上查找最近的普通函数并继承
const obj = {
name: 'obj',
fun1: function() {
console.log(this.name) // 'obj'
const fun1Inner = () => {
console.log(this.name) // 定义时的作用域绑定,此时作用域时fun1,而fun1的this指向obj
};
fun1Inner();
};
fun2: () => {
console.log(this.name) // 调用时因为obj是一个对象,对象没有this,此时this指向window,而window没有name属性,输出undefined
}
}
obj.fun1();
// 输出两个obj
obj.fun2();
// 输出undefiner