【JavaScript】箭头函数和普通函数的区别

发布于:2025-07-30 ⋅ 阅读:(13) ⋅ 点赞:(0)

⚙️ ​​1. 语法与定义​

  • ​普通函数​​:
    使用 function 关键字声明,支持具名或匿名形式:

    function add(a, b) { return a + b; } // 具名
    const sum = function(a, b) { return a + b; }; // 匿名
    
  • ​箭头函数​​:
    使用 => 定义,​​均为匿名函数​​,单行时可省略 {}return

    const add = (a, b) => a + b; // 隐式返回
    const log = () => { console.log("Hi"); }; // 显式代码块
    

    ​特点​​:语法更简洁,适合回调函数和简单逻辑。


🧭 ​​2. this 绑定机制(核心区别)​

  • ​普通函数​​:
    this​动态绑定​​,取决于调用时的上下文:

    const obj = {
      name: "Alice",
      greet: function() { console.log(this.name); } // this 指向 obj
    };
    obj.greet(); // 输出 "Alice"
    

    若单独调用,this 可能指向全局对象(非严格模式)或 undefined(严格模式)。

  • ​箭头函数​​:
    this​词法绑定​​,继承定义时的外层作用域,​​不可被修改​​:

    const obj = {
      name: "Alice",
      greet: () => { console.log(this.name); } // this 指向 window
    };
    obj.greet(); // 输出 "undefined"(浏览器环境)
    

    嵌套场景下,箭头函数继承最近普通函数的 this

    const obj = {
      name: "Alice",
      inner: function() {
        const arrow = () => console.log(this.name); // this 继承 inner 的 this(指向 obj)
        arrow();
      }
    };
    obj.inner(); // 输出 "Alice"
    

    ​注意​​:call/apply/bind​无法改变​​箭头函数的 this


🔧 ​​3. 构造函数与原型​

  • ​普通函数​​:
    支持 new 实例化,拥有 prototype 属性,用于实现面向对象编程:

    function Person(name) { this.name = name; }
    const john = new Person("John"); // 正常创建实例
    
  • ​箭头函数​​:
    ​不能作为构造函数​​,无 prototype 属性,使用 new 会报错:

    const Person = (name) => { this.name = name; };
    const jane = new Person("Jane"); // 报错:Person is not a constructor
    

📦 ​​4. 参数对象 arguments

  • ​普通函数​​:
    内置 arguments 类数组对象,存储所有传入参数:

    function showArgs(a, b) { console.log(arguments); }
    showArgs(1, 2); // 输出 [1, 2]
    
  • ​箭头函数​​:
    ​无 arguments 对象​​,需用 ...rest 参数替代:

    const showArgs = (...args) => console.log(args);
    showArgs(1, 2); // 输出 [1, 2]
    

⚠️ ​​5. 其他区别​

​特性​ ​普通函数​ ​箭头函数​
​原型链​ prototype 属性 prototype
​生成器函数​ 支持 yieldfunction* 不支持 yield
​严格模式下的 this 可设为 undefined 继承外层,不受严格模式影响
​方法定义​ 适合对象方法(需动态 this 不适合(this 固定)

🎯 ​​6. 使用场景建议​

  • ​推荐箭头函数​​:

    • 回调函数(如 setTimeoutmap)避免 this 丢失:

      const obj = {
        data: [1, 2, 3],
        process: function() {
          this.data.forEach(item => console.log(item * 2)); // this 指向 obj
        }
      };
      
    • 需要固定 this 的场合(如闭包嵌套)。

  • ​推荐普通函数​​:

    • 构造函数(new 实例化)。
    • 对象方法(需动态 this)。
    • 需要 arguments 或生成器(function*)的场景。

网站公告

今日签到

点亮在社区的每一天
去签到