箭头函数和普通函数有什么区别
时间: 2023-03-29 09:01:16 浏览: 145
箭头函数和普通函数的区别在于语法和作用域。箭头函数使用箭头(=>)来定义函数,而普通函数使用function关键字。箭头函数没有自己的this,它的this是继承自父级作用域的this,而普通函数的this是在运行时确定的。此外,箭头函数没有arguments对象,也不能用作构造函数。
相关问题
箭头函数和普通函数有什么区别?箭头函数为什么不嫩用作构造函数
箭头函数和普通函数的区别主要体现在以下几个方面:
1. 箭头函数没有自己的this值,它的this值继承自父执行上下文中的this值,而普通函数的this值则由函数被调用的方式来决定。
2. 箭头函数不能使用arguments对象来获取函数的参数,而是使用rest参数(...)来获取函数的参数,普通函数可以使用arguments对象或者rest参数来获取函数的参数。
3. 箭头函数不能作为构造函数使用,因为它没有自己的this值,而构造函数需要使用this来指向新创建的对象。
为什么箭头函数不能用作构造函数呢?因为箭头函数没有自己的this值,使用new操作符调用箭头函数时,它的this值会指向全局对象或者父执行上下文中的this值,这样就无法正常地创建新的对象,因此箭头函数不能用作构造函数。
箭头函数和普通函数有什么区别?
箭头函数和普通函数在JavaScript中有一些显著的区别,主要体现在语法、this指向、arguments对象和构造函数的使用上。以下是它们的主要区别:
1. **语法**:
- 普通函数:
```javascript
function functionName(params) {
// 函数体
}
```
- 箭头函数:
```javascript
const functionName = (params) => {
// 函数体
};
```
2. **this指向**:
- 普通函数的`this`指向调用它的对象,可以通过`call`、`apply`或`bind`来改变。
- 箭头函数的`this`在定义时就已经确定,并且不会改变。它会捕获其所在上下文的`this`值。
3. **arguments对象**:
- 普通函数有一个`arguments`对象,可以访问所有传入的参数。
- 箭头函数没有自己的`arguments`对象,它会捕获其所在上下文的`arguments`值。
4. **构造函数**:
- 普通函数可以作为构造函数使用,通过`new`关键字实例化对象。
- 箭头函数不能作为构造函数使用,不能通过`new`关键字实例化对象。
5. **返回值**:
- 普通函数需要显式使用`return`语句返回值。
- 箭头函数可以省略`return`语句和花括号,直接返回表达式结果。
示例:
```javascript
// 普通函数
function add(a, b) {
return a + b;
}
// 箭头函数
const add = (a, b) => a + b;
// this指向示例
function Person() {
this.age = 0;
setInterval(function growUp() {
this.age++;
}, 1000);
}
function Person() {
this.age = 0;
setInterval(() => {
this.age++;
}, 1000);
}
// arguments对象示例
function foo() {
console.log(arguments);
}
const bar = () => {
console.log(arguments);
};
// 构造函数示例
function Car(make, model) {
this.make = make;
this.model = model;
}
const myCar = new Car('Honda', 'Civic');
const Bike = (make, model) => {
this.make = make;
this.model = model;
};
const myBike = new Bike('Yamaha', 'YZF'); // TypeError: Bike is not a constructor
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)