常规函数与箭头函数

2025-06-07

常规函数与箭头函数

以多种方式定义您的功能。

一种方法是使用function关键字:

// function declaration
function test(msg) {
    return `Hey ${msg}`
}

// function expression
const test = function(msg) {
    return `Hey ${msg}`
}
Enter fullscreen mode Exit fullscreen mode

您可以将函数声明表达式称为普通函数

箭头函数是ES6中引入的,也称为胖箭头函数。

const arrowFunction = (msg) => {
    return `Hey ${msg}`
}
Enter fullscreen mode Exit fullscreen mode

正如你所见,上面例子中两个函数的工作原理相同。现在的问题是,为什么我们需要常规函数或箭头函数。

下面我们来讨论一下👇

1.语法

2.参数绑定

3.这个

4. new 关键字

5.没有重复的命名参数

6.函数提升

7.方法

1️⃣ 语法

我们可以用这种方式编写普通函数和箭头函数😎

// ES5
var add = function(x, y) {
    return x + y
};

// ES6
let add = (x, y) =>  x + y 
Enter fullscreen mode Exit fullscreen mode

隐性回报

在常规函数中,必须使用 return 关键字才能返回任何值。如果不返回任何值,函数将返回 undefined。

function regFunc() {
    return "Regular Function";
}
regFunc(); 
// Regular Function

function regFunc() {
    console.log("Regular Function")
}
regFunc(); 
// Regular Function
// undefined
Enter fullscreen mode Exit fullscreen mode

箭头函数在返回值时的行为方式相同。

如果箭头函数包含一个表达式,则可以省略花括号,然后隐式返回该表达式。

{}如果只有一行语句则不需要

const addOne = (number) => number + 1;
addOne(10);
Enter fullscreen mode Exit fullscreen mode

()如果只传递一个参数则不需要

let add = x => x + x;
Enter fullscreen mode Exit fullscreen mode

如果没有争论

let arrowFunc = _ => console.log("Arrow Function");
Enter fullscreen mode Exit fullscreen mode

2️⃣ 参数绑定

在常规功能中,参数关键字可用于访问传递给函数的参数。

例子:

function regularFunction(a,b) {
    console.log(arguments)
}

regularFunction(1,2)
// Arguments[1,2]
Enter fullscreen mode Exit fullscreen mode

箭头函数没有参数绑定。

const arrowFunction = (a,b) => {
    console.log(arguments)
}

arrowFunction(1,2)
//ReferenceError: argumnets is not defined
Enter fullscreen mode Exit fullscreen mode

但是,如果要访问箭头函数中的参数,则可以使用 rest 运算符:

var arrowFunction = (...args) => {
    console.log(...args)
}

arrowFunction(1,2)
// 1 2
Enter fullscreen mode Exit fullscreen mode

3️⃣这个

在常规函数中,这会根据函数的调用方式而变化。

  • 简单调用: this 等于全局对象,如果使用严格模式则可能未定义。
  • 方法调用: this 等于拥有该方法的对象。
  • 间接调用: this 等于第一个参数。
  • 构造函数调用: this 等于新创建的实例。
// 1️⃣ Simple Invocation
function simpleInvocation() {
    console.log(this);
}

simpleInvocation(); 
// Window Object


// 2️⃣ Method Invocation
const methodInvocation = {
  method() {
      console.log(this);
  }
};

methodInvocation.method(); 
// logs methodInvocation object


// 3️⃣ Indirect Invocation
const context = { aVal: 'A', bVal: 'B' };
function indirectInvocation() {
    console.log(this);
}

indirectInvocation.call(context);  // logs { aVal: 'A' }
indirectInvocation.apply(context); // logs { bVal: 'A' }


// 4️⃣ Constructor Invocation
function constructorInvocation() {
    console.log(this);
}

new constructorInvocation(); 
// logs an instance of constructorInvocation
Enter fullscreen mode Exit fullscreen mode

箭头函数没有自己的this,并且不会this在函数内重新定义的值。

this箭头函数内部总是从外部上下文引用 this。

var name = "Suprabha"
let newObject = {
    name : "supi",
    arrowFunc: () => {
        console.log(this.name); 
    },
    regularFunc() {
        console.log(this.name); 
    }   
}

newObject.arrowFunc(); // Suprabha
newObject.regularFunc(); // supi
Enter fullscreen mode Exit fullscreen mode

4️⃣个新品

常规函数是可构造的,可以使用 new 关键字调用它们。

function add (x, y) {
    console.log(x + y)
}

let sum = new add(2,3);
// 5
Enter fullscreen mode Exit fullscreen mode

然而,箭头函数永远不能用作构造函数。因此,它们永远不能用 new 关键字调用。

let add = (x, y) => console.log(x + y);

const sum = new add(2,4); 
// TypeError: add is not a constructor
Enter fullscreen mode Exit fullscreen mode

5️⃣ 没有重复的命名参数

在正常功能中,我们可以这样做:

// ✅ will work 
function add(a, a) {}

// ❌ will not work 
'use strict';
function add(a, a) {}

// Uncaught SyntaxError: Duplicate parameter name not allowed in this context
Enter fullscreen mode Exit fullscreen mode

无论在严格模式还是非严格模式下,箭头函数都不能有重复的命名参数。

const arrowFunc = (a,a) => {}

// Uncaught SyntaxError: Duplicate parameter name not allowed in this context
Enter fullscreen mode Exit fullscreen mode

6️⃣ 函数提升

在常规函数中,函数在顶部被提升。

normalFunc()

function normalFunc() {
    return "Normal Function"
}

// "Normal Function"
Enter fullscreen mode Exit fullscreen mode

在箭头函数中,函数会在定义的位置被提升。因此,如果在初始化之前调用该函数,将会引发引用错误 (referenceError)。

arrowFunc()

const arrowFunc = () => {
    return "Arrow Function"
}

// ReferenceError: Cannot access 'arrowFunc' before initialization
Enter fullscreen mode Exit fullscreen mode

7️⃣ 种方法

您可以使用常规函数在类中定义方法。

class FullName {
    constructor(name) {
        this.name = name;
    }

    result() {
        console.log(this.name)
    }
}

let name = new FullName("Suprabha")

console.log(name) 
// FullName {name: "Suprabha"}
Enter fullscreen mode Exit fullscreen mode

您还需要将方法应用为回调。

setTimeout(name.result, 2000) 
// after 1 second logs ""
Enter fullscreen mode Exit fullscreen mode

但如果你绑定this

setTimeout(name.result.bind(name), 2000) 
// Suprabha
Enter fullscreen mode Exit fullscreen mode

通过上面的例子,您可以看到您必须将 this 绑定到上下文。

在箭头函数中,您不必与上下文绑定。

class FullName {
    constructor(name) {
        this.name = name;
    }

    result = () => {
        console.log(this.name)
    }
}

let name = new FullName("Suprabha")

setTimeout(name.result, 2000) // Suprabha
Enter fullscreen mode Exit fullscreen mode

何时不使用箭头函数👩🏻‍💻

对象方法

let dog = {
    count: 3,
    jumps: () => {
        this.count++
    }
}
Enter fullscreen mode Exit fullscreen mode

当你调用 时dog.jumps, count 的值不会增加。这是因为 this 没有绑定任何东西,它会从其父作用域继承 this 的值。

参考🧐

概括

在常规函数中,this值是动态的,在箭头函数中它等于外部函数的 this。

在常规函数中,参数将为您提供函数中传递的参数列表,在箭头函数中未定义参数。

在常规函数中,您总是必须返回任何值,但在箭头函数中,您可以跳过 return 关键字并在一行中写入。

在箭头函数中,参数应该是唯一的。

箭头函数中的提升很重要,因为函数在初始化之前不会被调用。



感谢您阅读这篇文章❤️

给我买杯咖啡

🌟推特 📚电子书 🌟 Instagram
文章来源:https://dev.to/suprabhasupi/regular-vs-arrow-function-4kpe
PREV
从数组中删除重复的值
NEXT
学习在 React Prettier 中配置 ESLINT 和 PRETTIER 🗽 husky 🐶