[英]Javascript Function Parameter argument or global variable
var x=10;
function foo(){
x=120;
alert(arguments[0]); //outputs 10
}
foo(x);
如何知道函数中使用的x
是参数还是全局变量?
如果我提供了这个
function foo(x){
x=120;
console.log(arguments[0]);//logs 120
}
foo(x);
这两个代码之间有什么区别,幕后发生了什么以及参数数组如何变化?
var x=10; // this is variable of window namespace
function foo(x){
// It will make variable of this functions. Every function make its own namespace.
// So now you have x in local namespace, so you can't touch x from global
// namespace, becouse you gave them same names. With for example function foo(a),
// global x would be still accessible.
x=120;
// Here, you change value of x. Program will ask the deepest namespace if there
// is any x variable. If not, it will continue upper and upper. Right now,
// we have local x variable, so it will change value of local variable, which
// will extinct at the end of our function. The most upper namespace is global
// namespace. One more deeper is window namespace.
alert(arguments[0]);
// arguments is Array, which every function has as its property. Via arguments,
// you can touch every argument, that is passed to function. Later, I will
// show you an example
}
foo(12);
// finaly here, you call function foo and you set local x = 12. But then,
// you rewrite local x, so it is 120. After all, you alert first argument,
// which is local x, which is 120.
现在进行修改:
var x=10;
function foo(a){ // now we have different name for local variable
x=120; // so our x is x from window namespace
alert(arguments[0]); // now output is a, which will be 12
alert(x); // and x is 120
}
foo(12);
alert(x); // x will be still 120...
带有论点的不同故事
var x=10;
function foo(){ // we didnt declare any local variable
x=120; // so our x is x from window namespace again
alert(arguments[0]);
// output is 12, becouse we can touch arguments via
// arguments array, even if we didnt declare any local variables
}
foo(12);
基本上,arguments函数的属性允许我们做魔术。 它使代码难以理解,但功能非常强大。 很少有使用它们的好主意。 明智地使用它们...
参数和局部变量指向内存中的同一位置。 因此,更改一个将立即更改另一个。
我怎么知道在函数内使用的xim是参数还是全局变量?
通过检查函数的参数列表。 如果它提到这样的参数x
:
function foo(x) {
那么您知道x
是一个参数。 它是arguments[0]
的别名(别名),因为它是第一个参数。 arguments
对象不是真正的数组。 它具有名称为数字的属性,并且具有length属性,因此它看起来像一个数组,但是缺少数组的其他功能。
您可以将arguments
视为函数调用中传递的值的最终存储。 参数名称是获取存储在arguments
中的值的便捷方法。
如果您的职能开始:
function foo() {
那么它没有参数。 您在函数内部引用的任何内容都必须是用另一种方式定义的值。 它可能是在函数内部声明的局部变量:
function foo() {
var x = 10;
或者它可以引用函数外部声明的名称:
var x;
function foo() {
x = 10;
在没有“严格模式”的JavaScript中,可以这样说:
function foo() {
x = 10;
无需在任何地方声明var x
。 结果是x将被创建为全局变量(或全局对象的属性,例如在浏览器中将创建window.x
)。这是大量的bug,因为您可能会拼写变量名而不会注意到您给一个不存在的变量赋值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.