箭头函数的this指向谁
时间: 2023-09-14 14:04:25 浏览: 48
箭头函数的 this 指向与普通函数不同,它没有自己的 this 绑定,而是继承了上一层执行上下文的 this 值。简单来说,箭头函数的 this 指向是词法作用域中的 this,也就是定义时的 this,而不是运行时的 this。这个特性使得箭头函数在处理回调函数时非常方便,因为它可以避免 this 指向的混乱问题。
相关问题
箭头函数this指向
箭头函数的 this 指向是在定义函数时确定的,而不是在运行时确定的。箭头函数没有自己的 this 绑定,它会继承外层作用域的 this 值。这意味着箭头函数内部的 this 与外部的 this 是一致的,与箭头函数被调用的方式无关。
相反,普通函数的 this 指向是在函数被调用时根据调用方式动态确定的。通常情况下,this 的值取决于调用函数的对象。
这是一个箭头函数和普通函数的示例来说明它们之间的差异:
```javascript
const obj = {
name: "C知道",
arrowFunc: () => {
console.log(this.name); // undefined
},
regularFunc: function() {
console.log(this.name); // C知道
}
};
const arrowFunc = obj.arrowFunc;
const regularFunc = obj.regularFunc;
arrowFunc();
regularFunc();
```
在箭头函数中,this.name 打印出 undefined,因为箭头函数继承了外层作用域的 this(在此示例中为全局对象,即 Window 对象),而全局对象没有 name 属性。
而在普通函数中,this.name 打印出 "C知道",因为它的 this 绑定是根据调用方式动态确定的,而在此示例中该函数是作为 obj 对象的方法调用的,所以 this 绑定到了 obj 对象。
总结起来,箭头函数的 this 是静态的,继承自外层作用域的 this;而普通函数的 this 是动态的,根据调用方式决定。
箭头函数 this指向
箭头函数的this指向是继承而来的,并且指向在定义它时所处的对象,即父级作用域,而不是执行时的对象。这意味着箭头函数内部的this的值不会受到函数调用方式的影响,而是固定指向外层代码块的this。这种特性让箭头函数在使用setTimeout、setInterval等场景下更加方便地使用this。所以,无论箭头函数在哪里被调用,它的this都指向定义它的外层代码块的this,而不是调用时的对象。这与传统的函数的运行机制不同,传统的函数中的this是动态绑定的,它的值会根据函数的调用方式来决定。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [箭头函数this的指向](https://blog.csdn.net/weixin_57959921/article/details/129439200)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [关于箭头函数中的this的指向](https://blog.csdn.net/xu4321083/article/details/79753800)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [箭头函数及其this的指向](https://blog.csdn.net/qq_53841687/article/details/125770647)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]