函数参数 [英] function arguments
问题描述
function Foo(f) {
var f = f;
}
这里面的函数,变量 f
是 Foo
的本地(它有一个函数范围),但为什么变量 f
in参数列表没有冲突?也许是因为它绑定在 Foo.arguments
对象中?
Here inside the function, variable f
is local to the Foo
(it has a function scope), but why is the variable f
in the argument list not in conflict? Maybe because it is bound inside the Foo.arguments
object?
在其他语言中我们不能声明一个参数变量与本地变量同名。
In other languages we cannot declare an argument variable with the same name as a local variable.
这个名称歧义是如何解决的?或者,如何在方法中稍后引用两个不同的 f
变量中的每一个?
How is this name ambiguity resolved? Or, How do you reference each of the two distinct f
variables later in the method?
推荐答案
JavaScript做了一些显然不直观的事情 - 你感兴趣的事情被称为提升 - JS将var声明移动到函数的顶部,它们的唯一目的是将此变量名称保留为函数范围中的局部变量。有时,这会导致很多奇怪。如果变量名已经被保留为局部变量(例如它是一个参数),var声明将完全被删除。
JavaScript does a couple of things that aren't obviously intuitive - the one you're interested in is called "hoisting" - JS moves var declarations to the top of a function, where they serve the sole purpose of reserving this variable name as a local variable in the function's scope. Sometimes, this leads to lots of weirdness. If the variable name is already reserved as a local variable (e.g. it's an argument) the var declaration gets dropped entirely.
JS的另一个不直观的部分是它如何处理参数变量和参数
对象(有点特殊,正如Hippo所示)。但这并不一定是你感兴趣的 - 对你的例子来说重要的是参数还声明变量名称是函数的本地名称。
Another unintuitive part of JS is how it deals with argument variables and the arguments
object (which are a bit special, as Hippo showed). That's not necessarily what you're interested in, though - what's important for your example is that arguments also declare that variable name as local to the function.
所有结果这是当你有一个 var f
以及一个参数名 f
时,`var f'会被删除,你的例子相当于:
The result of all this is that when you have a var f
as well as an argument name f
, the `var f' gets dropped, and your example is equivalent to:
function Foo(f) {
f = f;
}
你可以在Hippo的例子中看到这个,因为:
You can see this in Hippo's example, because:
function foo(f) {
console.log(f); // --> 11
console.log(arguments); // --> array [11]
var f = 10;
console.log(f); // --> 10
console.log(arguments); // --> [10] (!!!)
}
相当于:
function foo(f) {
var f;
console.log(f); // --> 11
console.log(arguments); // --> array [11]
f = 10;
console.log(f); // --> 10
console.log(arguments); // --> [10] (!!!)
}
相当于:
function foo(f) {
console.log(f); // --> 11
console.log(arguments); // --> array [11]
f = 10;
console.log(f); // --> 10
console.log(arguments); // --> [10] (!!!)
}
有关详细信息,请阅读 10.1.3 - 变量实例化(第37页底部) ECMA-262 ,JS规范。
For more details, read up section 10.1.3 - Variable Instantiation (bottom of p.37) in ECMA-262, the JS specification.
这篇关于函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!