为什么默认参数在 javascript 中的函数内部是不可变的?

如何解决为什么默认参数在 javascript 中的函数内部是不可变的?

为什么在 javascript 中,默认参数不能在函数内部更改而非默认参数可以?

function func(a) {
  a = 99; // updating a also updates arguments[0]
  console.log(arguments[0]);
}
func(10); // prints 99

对比

function func(a = 55) {
  arguments[0] = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // prints 10

解决方法

看着MDN Web Docs

仅传递简单参数的非严格函数(即,不是rest、默认或重组参数)会将函数体中的变量新值与arguments对象同步,反之亦然:

function func(a) {
  arguments[0] = 99; // updating arguments[0] also updates a
  console.log(a);
}
func(10); // 99

还有

function func(a) {
  a = 99; // updating a also updates arguments[0]
  console.log(arguments[0]);
}
func(10); // 99

相反,传递rest、default 或解构参数的非严格函数不会将分配给函数体中的参数变量的新值与参数对象同步。相反,具有复杂参数的非严格函数中的 arguments 对象将始终反映调用函数时传递给函数的值(这与所有严格模式函数表现出的行为相同,无论它们是什么类型的变量)通过):

function func(a = 55) {
  arguments[0] = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // 10

function func(a = 55) {
  a = 99; // updating a does not also update arguments[0]
  console.log(arguments[0]);
}
func(10); // 10

还有

// An untracked default parameter
function func(a = 55) {
  console.log(arguments[0]);
}
func(); // undefined

这可能是由于 javascript 编译器中的同步过程语法糖存在一些问题。

更新:

事实证明,deno 正在做一些不同的事情,并且在这两种情况下打印 10 这有点奇怪,所以我查看了此处生成的程序集:

deno eval 'function f(a) { a = 99; console.log(arguments[0]); } f(10);' --v8-flags='--print-bytecode,--print-bytecode-filter=f'
deno eval 'function f(a = 55) { arguments[0] = 99; console.log(a); } f(10);' --v8-flags='--print-bytecode,--print-bytecode-filter=f'

第一个命令打印这段代码,我试图理解它,在我认为它正在做一些相关的事情的地方添加注释。

[generated bytecode for function: f (0x38db0826b679 <SharedFunctionInfo f>)]
Parameter count 2
Register count 4
Frame size 32
    0x38db0826b846 @    0 : 88                CreateUnmappedArguments
    0x38db0826b847 @    1 : 26 fb             Star r0: Store accumulator in register 0 (presumibly function frame pointer)
    0x38db0826b849 @    3 : 0c 63             LdaSmi [99]: Load (SMallInteger) 99 in accumulator
    0x38db0826b84b @    5 : 26 02             Star a0: Store accumulator in function argument 0
    0x38db0826b84d @    7 : 13 00 00          LdaGlobal [0],[0]: I don't know
    0x38db0826b850 @   10 : 26 f9             Star r2: Store accumulator in register 2
    0x38db0826b852 @   12 : 28 f9 01 02       LdaNamedProperty r2,[1],[2]: Load a in the accumulator
    0x38db0826b856 @   16 : 26 fa             Star r1: Store accumulator in register 1
    0x38db0826b858 @   18 : 0b                LdaZero: Load 0 in accumulator
    0x38db0826b859 @   19 : 2a fb 04          LdaKeyedProperty r0,[4]: (presumibly) loading the property with key 4
                                                                        from the function frame with the accumulator
                                                                        (syncing) the argument here.
    0x38db0826b85c @   22 : 26 f8             Star r3: Store accumulator in register 3
    0x38db0826b85e @   24 : 59 fa f9 f8 06    CallProperty1 r1,r2,r3,[6]: console.log(r1)
    0x38db0826b863 @   29 : 0d                LdaUndefined: Load undefined in accumulator
    0x38db0826b864 @   30 : aa                Return: Return the accumulator value
Constant pool (size = 2)
Handler Table (size = 0)
Source Position Table (size = 0)

这是我处理的第二个程序的输出:

[generated bytecode for function: f (0x3bd80826b679 <SharedFunctionInfo f>)]
Parameter count 2
Register count 4
Frame size 32
    0x3bd80826b846 @    0 : 88                CreateUnmappedArguments
    0x3bd80826b847 @    1 : 26 fa             Star r1: Store accumulator in register 1 (presumibly function frame pointer)
    0x3bd80826b849 @    3 : 25 02             Ldar a0: Load in the accumulator the argument 0
    0x3bd80826b84b @    5 : 9e 06             JumpIfNotUndefined [6] (0x3bd80826b851 @ 11): If accumulator is undefined:
    0x3bd80826b84d @    7 : 0c 37                 LdaSmi [55]: Load (SMallInteger) 55 in accumulator
    0x3bd80826b84f @    9 : 8b 04             Jump [4] (0x3bd80826b853 @ 13): else:
    0x3bd80826b851 @   11 : 25 02                 Ldar a0: Load argument 0 in accumulator
    0x3bd80826b853 @   13 : 26 fb             Star r0: Store accumulator in register 0
    0x3bd80826b855 @   15 : 0b                LdaZero: Load 0 in accumulator
    0x3bd80826b856 @   16 : 26 f8             Star r3: Store accumulator in register 3
    0x3bd80826b858 @   18 : 0c 63             LdaSmi [99]: Load (SMallInteger) 99 in accumulator
    0x3bd80826b85a @   20 : 30 fa f8 00       StaKeyedProperty r1,[0]: (presumibly) loading in the function frame
                                                                            (r1) the value of the accumulator (99) in the
                                                                            property with key r3 (0) (syncing)
    0x3bd80826b85e @   24 : 13 00 02          LdaGlobal [0],[2]: (presumibly) loading the global value containing the
                                                                  pointer to a in the accumulator
    0x3bd80826b861 @   27 : 26 f8             Star r3: Store accumulator in register 3
    0x3bd80826b863 @   29 : 28 f8 01 04       LdaNamedProperty r3,[4]: Load a in the accumulator
    0x3bd80826b867 @   33 : 26 f9             Star r2: Store accumulator in register 2
    0x3bd80826b869 @   35 : 59 f9 f8 fb 06    CallProperty1 r2,r0,[6]: console.log(r2)
    0x3bd80826b86e @   40 : 0d                LdaUndefined: Load undefined in accumulator
    0x3bd80826b86f @   41 : aa                Return: Return the accumulator value
Constant pool (size = 2)
Handler Table (size = 0)
Source Position Table (size = 0)

如您所见,第二个代码与第一个类似,只是添加了一个 if 语句来检查可选参数。

最后,v8 google engine 中的 deno 打印 10 两次。 这很奇怪,但我认为发生这种情况是有原因的。 可能是有人在他们的实施中做出了这个决定,而不是每个人都反映了这一变化。但是,请不要烤我,我已经尽力在没有手册的情况下理解字节码,所以如果有错误,请告诉我,我会修复它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-