You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在函数体内重赋值函数名会改变函数行为?

fun1与fun2的核心差异解析

1. fun1的工作逻辑:闭包+自重定义

第一次调用fun1时,会执行以下步骤:

  • 在函数内部创建const arr = ["a", "b", "c", "d", "e"]数组;
  • 把全局的fun1变量重新赋值为一个新函数,这个新函数借助JavaScript闭包特性,会永久捕获并保留对第一次创建的arr的引用;
  • 最后调用这个重定义后的fun1,返回arr的引用。

从第二次调用开始,fun1已经变成了那个重定义后的函数,每次调用都会直接返回第一次创建的arr引用。所以修改返回的数组后,后续调用拿到的始终是同一个被修改过的数组。

2. fun2的工作逻辑:普通函数的作用域

fun2是一个普通函数,每次调用都会在自身作用域内创建一个全新的arr数组,然后返回这个新数组的引用。所以每次调用fun2拿到的都是独立的新数组,修改前一次返回的数组不会影响下一次调用的结果。

测试代码验证

// 自重定义+闭包的函数
function fun1() {
  const arr = ["a", "b", "c", "d", "e"];
  fun1 = function() {
    return arr;
  };
  return fun1();
}

// 普通函数
function fun2() {
  const arr = ["a", "b", "c", "d", "e"];
  return arr;
}

// 测试fun1
let test_fun_1 = fun1();
test_fun_1.pop();
test_fun_1 = fun1();
console.log("Logging test_fun_1");
console.log(test_fun_1); // ["a", "b", "c", "d"]

// 测试fun2
let test_fun_2 = fun2();
test_fun_2.pop();
test_fun_2 = fun2();
console.log("Logging test_fun_2");
console.log(test_fun_2); // ["a", "b", "c", "d", "e"]

内容的提问来源于stack exchange,提问作者0xRyN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 18:28:26