gpt4 book ai didi

javascript - 命名参数和 JavaScript 中的参数对象

转载 作者:数据小太阳 更新时间:2023-10-29 03:53:01 27 4
gpt4 key购买 nike

最近我开始通过 Nicholas C. Zakas 的书 Professional JavaScript For Web Developers 学习 JavaScript,我遇到了一些我自己无法解决的问题。

正如标题所说,这就是关于 JavaScript 函数中的命名参数参数对象的全部内容。

例如我们有这段代码:

function doAdd(num1 , num2) {
arguments[1] = 10;
alert(arguments[0] + num2);
}

doAdd(10 , 20);

书上说参数对象中的值会自动反射(reflect)在相应的命名参数中,因此 num2输入值为 20 的函数,然后通过 arguments[1] 覆盖它最后得到一个值 10。到此为止一切都很好。然后它说

this effect goes only one way: changing the named argument does not result in a change to the corresponding value in arguments.

这就是问题的开始。

我试图稍微修改这段代码以理解作者所说的内容,但我失败了。

例如

function doAdd(num1 , num2) {
arguments[1] = 10;
num2 = 40;
alert(arguments[0] + arguments[1]);
}

doAdd(10 , 20);

这次num2再次输入值为 20 的函数,它通过 arguments[1] 更改为 10然后通过命名参数 num2 再次变为 40这次。弹出警报 50,因为对 named 参数的更改不会导致 arguments 中相应值的更改。 .为什么alert不弹出20

最佳答案

这是因为本书假定您使用的是 strict mode .

如果您在严格模式下运行代码,您将获得书中所写的预期行为。

function doAdd(num1 , num2) {
"use strict";
arguments[1] = 10;
num2 = 40;
alert(arguments[0] + arguments[1]);
}
doAdd(10 , 20); // this alerts 20, alerts 50 in nonstrict mode

一个鲜为人知的事实是,严格模式的全部意义在于避免这种动态范围界定(这就是为什么参数是固定的,with 是不允许的,eval 表现不同)。除了提高清晰度之外,这还可以显着提高速度。

另见 this :

For strict mode functions, the values of the arguments object‘s properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.

这就是 NCZ 在上下文中的意思,引用了这本书本身:

Strict mode makes several changes to how the arguments object can be used. First, assignment, as in the previous example, no longer works. The value of num2 remains undefined even though arguments[1] has been assigned to 10. Second, trying to overwrite the value of arguments is a syntax error. (The code will not execute.) - Page 82, Language Basics, Professional JavaScript, Nicholas C. Zakas

关于javascript - 命名参数和 JavaScript 中的参数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722362/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com