JavaScript:箭头函数与普通函数的区别与适用场景

1 箭头函数与普通函数的区别

1.1 语法上的区别

箭头函数使用箭头(=>)来定义函数,而普通函数使用function关键字来定义函数。

箭头函数通常是 匿名函数,所以需要将其赋值给一个变量或者作为参数传递给另一个函数。

示例:

// 普通函数
function add01(x, y) {
    
    
    return x + y;
}

console.log('普通函数输出结果:', add01(1,3));	//普通函数输出结果: 4

// 箭头函数,赋值给一个变量
const add02 = (x, y) => {
    
    
    return x + y;
};

console.log('箭头函数输出结果:', add02(1,3));	//箭头函数输出结果: 4

// 箭头函数作为参数传递给另一个函数
function myFunc(res) {
    
    
    res();
}

myFunc(() => {
    
    
    var a = 10;
    console.log('箭头函数作为普通函数的参数:', a);
});	//箭头函数作为普通函数的参数: 10

1.2 this指向的区别

在普通函数中,this指向的是调用该函数的对象,也就是函数的执行上下文。而在箭头函数中,this指向的是定义该箭头函数时所在的上下文,也就是箭头函数所在的函数或者全局对象。

示例:

var name = 'Jerry';

// 普通函数中的this
const person01 = {
    
    
  name: 'Tom',
  age: '18',
  sayHi: function() {
    
    
    console.log(`Hi, my name is ${
      
      this.name}.`);
    console.log(`Hi, my age is ${
      
      this.age}.`);
  }
};
person01.sayHi(); // Hi, my name is Tom. Hi, my age is 18.

// 箭头函数中的this
const person02 = {
    
    
  name: 'Tom',
  age: '18',
  sayHi: () => {
    
    
    console.log(`Hi, my name is ${
      
      this.name}.`);
    console.log(`Hi, my age is ${
      
      this.age}.`);
  }
};
person02.sayHi(); // Hi, my name is Jerry. Hi, my name is undefined.

在上面的例子中,普通函数中的this指向的是person对象,而箭头函数中的this指向的是全局对象(因为箭头函数没有自己的this,所以它继承了外层函数的this值)。

完整代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var name = 'Jerry';

        // 普通函数中的this
        const person01 = {
      
      
            name: 'Tom',
            age: '18',
            sayHi: function () {
      
      
                console.log(`Hi, my name is ${ 
        this.name}.`);
                console.log(`Hi, my age is ${ 
        this.age}.`);
            }
        };
        person01.sayHi(); // Hi, my name is Tom. Hi, my age is 18.

        // 箭头函数中的this
        const person02 = {
      
      
            name: 'Tom',
            age: '18',
            sayHi: () => {
      
      
                console.log(`Hi, my name is ${ 
        this.name}.`);
                console.log(`Hi, my age is ${ 
        this.age}.`);
            }
        };
        person02.sayHi(); // Hi, my name is Jerry. Hi, my name is undefined.
    </script>
</body>

</html>

输出结果:

在这里插入图片描述

1.3 arguments对象的区别

在普通函数中,arguments对象是一个类数组对象,包含了函数所有的参数。

而在箭头函数中,arguments对象是不存在的,需要使用Rest参数来获取所有的参数,它允许函数接收任意数量的参数并将它们存储在一个数组中。Rest 参数使用三个点(...)符号表示,后面跟着一个参数名。当函数使用 Rest 参数时,它会将传递给函数的所有参数都放到一个数组中,并将该数组作为 Rest 参数的值传递给函数。例如:

const myFunction = (...args) => {
    
    
  console.log(args);
};
myFunction(1, 2, 3); // Output: [1, 2, 3]

示例:

// 普通函数中的arguments
function sum() {
    
    
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    
    
    total += arguments[i];
  }
  return total;
}
sum(1, 2, 3); // 6

// 箭头函数中的Rest参数
const sum = (...args) => {
    
    
  let total = 0;
  for (let i = 0; i < args.length; i++) {
    
    
    total += args[i];
  }
  return total;
};
sum(1, 2, 3); // 6

1.4 箭头函数不能用作构造函数

普通函数可以用作构造函数来创建对象,而箭头函数不能用作构造函数。

示例:

// 普通函数作为构造函数
function Person(name, age) {
    
    
  this.name = name;
  this.age = age;
}
const tom = new Person('Tom', 18);

// 箭头函数不能作为构造函数
const Person = (name, age) => {
    
    
  this.name = name;
  this.age = age;
};
const tom = new Person('Tom', 18); // TypeError: Person is not a constructor

2 箭头函数和普通函数的适用场景

2.1 普通函数的适用场景

2.1.1 构造函数

当你需要创建一个对象的实例时,通常会使用构造函数。在构造函数中,this 关键字指向新创建的对象实例。

function Person(name) {
    
    
  this.name = name;
}

const john = new Person('John');
console.log(john.name); // Output: John

2.1.2 方法

如果你需要在对象上定义一个方法,并且需要访问该对象的属性或方法,则应使用普通函数。

const obj = {
    
    
  name: 'John',
  sayHello: function() {
    
    
    console.log(`Hello ${
      
      this.name}`);
  }
};

obj.sayHello(); // Output: Hello John

2.1.3 回调函数

如果你需要将一个函数作为回调函数传递给其他函数,通常应该使用普通函数。因为其他函数可能会更改该函数的上下文。

示例代码: setTimeout() 函数。

function myCallback() {
    
    
  console.log('Callback executed!');
}

setTimeout(myCallback, 5000); // Output: Callback executed!

在调用setTimeout()函数时,myCallback()函数并没有立即执行,而是在等待一段时间后才执行。因此,上面的示例代码应该是在等待5000毫秒后才会在控制台输出"Callback executed!"。

2.2 箭头函数的适用场景

箭头函数适用于那些简短、简洁、明确的函数,可以使代码更加简洁易懂。

2.2.1 简答的回调函数

当需要传递一个简单的函数作为回调,箭头函数可以使代码更简洁。

示例:

// 普通函数
arr.forEach(function(item) {
    
    
  console.log(item);
});

// 箭头函数
arr.forEach(item => console.log(item));

2.2.2 隐式返回

当函数只有一行代码并且返回一个值时,可以使用箭头函数来隐式返回该值,这可以使代码更加简洁。

// 普通函数
function square(x) {
    
    
  return x * x;
}

// 箭头函数
const square = x => x * x;

猜你喜欢

转载自blog.csdn.net/weixin_46098577/article/details/131005395