箭头函数this指向问题,箭头函数与普通函数的区别?
时间: 2024-05-27 21:14:38 浏览: 18
箭头函数和普通函数最大的区别在于它们的this指向不同。
普通函数的this指向是动态的,在运行时根据调用时的上下文决定。当使用函数调用、对象方法调用或apply/call/bind等方法调用时,this指向的对象不同。
而箭头函数的this指向是静态的,即函数定义时所在的词法作用域的this值,无法通过任何方式改变this的指向。
这意味着,在箭头函数内部使用this时,它指向的是箭头函数所在的上下文,而不是函数调用时的上下文。这也是为什么箭头函数经常被用来解决this指向问题的原因。
相关问题
this指向(普通函数与箭头函数的this)?
在 JavaScript 中,函数的 this 关键字是指调用该函数的对象。但是普通函数和箭头函数对 this 的处理方式是不同的。
普通函数的 this 关键字指向的是调用函数的对象。如果函数是作为对象的方法被调用,那么 this 就指向该对象。如果函数是独立调用的,那么 this 就指向全局对象(在浏览器中就是 window 对象,在 Node.js 环境中就是 global 对象)。
箭头函数的 this 关键字是根据词法作用域来确定的。箭头函数的 this 指向的是定义该函数时所在的作用域中的 this,而不是调用该函数时所在的作用域中的 this。因此,箭头函数的 this 无法通过 bind、call 或 apply 改变它的指向。
箭头函数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 是动态的,根据调用方式决定。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)