箭头函数的this指向谁
- 游戏开发
- 2025-09-08 01:45:01

先看1个重要原则:
由Vue管理的函数,一定不要写箭头函数,箭头函数的this就不再是Vue实例了
箭头函数的 this 指向在定义时确定,继承自外层作用域(即定义时的上下文)的 this,且无法通过 call、apply 或 bind 改变。以下是关键点总结:
1. 词法作用域的 this箭头函数没有自己的 this,它使用外层非箭头函数作用域的 this 值。若外层没有函数,则指向全局对象(如 window 或 global)。
示例:
const obj = { value: 42, getValue: function() { // 普通函数中的 this 指向 obj const arrowFn = () => this.value; return arrowFn(); } }; console.log(obj.getValue()); // 输出 42 2. 与普通函数的区别普通函数:this 由调用方式决定(如对象方法、构造函数、事件监听等)。
箭头函数:this 固定为定义时的外层 this。
示例对比:
// 普通函数(this 指向调用者) const obj1 = { value: 10, fn: function() { console.log(this.value); } }; setTimeout(obj1.fn, 100); // 输出 undefined(this 指向全局) // 箭头函数(this 继承外层) const obj2 = { value: 10, fn: function() { setTimeout(() => console.log(this.value), 100); // 继承外层 this(obj2) } }; obj2.fn(); // 输出 10 3. 无法通过绑定方法修改使用 call、apply 或 bind 无法改变箭头函数的 this。
示例:
const outerThis = { name: "Outer" }; const arrowFn = () => console.log(this.name); arrowFn.call({ name: "New" }); // 输出 "Outer"(若外层 this 指向全局则可能输出 undefined) 4. 对象字面量中的陷阱对象字面量不创建作用域,内部箭头函数的 this 指向全局。
示例:
const obj = { value: "Hello", getValue: () => console.log(this.value) // this 指向全局(如 window) }; obj.getValue(); // 输出 undefined(假设外层为全局) 5. 在构造函数中的行为箭头函数作为构造函数会报错(不能 new)。
但若在构造函数内定义,箭头函数会继承实例的 this:
function Person() { this.age = 0; setInterval(() => { this.age++; // this 指向 Person 的实例 }, 1000); } const p = new Person(); // age 每秒自增 6.总结箭头函数的 this:继承自定义时的外层作用域,且不可更改。
使用场景:需要固定 this 时(如回调、事件处理、setTimeout)。
避免场景:需要动态 this 时(如对象方法、构造函数)。
通过理解箭头函数的词法 this 特性,可以更灵活地控制代码中的上下文绑定。
箭头函数的this指向谁由讯客互联游戏开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“箭头函数的this指向谁”