Javascript 函数参数参数或全局变量

标签 javascript variables arguments

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);

基本上,参数函数属性允许我们进行黑魔法。它使代码不太容易理解,但它非常强大。很少情况下,使用它们是个好主意。明智地使用它们...

参数和局部变量指向内存中的同一位置。因此,改变一个就会立即改变另一个。

关于Javascript 函数参数参数或全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18081440/

相关文章:

javascript - 从链表中删除奇数/偶数

javascript - HTML 连接 img 标签内的跨度

Javascript图像宽度和高度未定义值

php - 将列拆分为单独的变量

c - 可以将实际参数定义为 `const int` 但在 header 中将其声明为 `int` 吗?

javascript - 从 Web 到移动设备的 Firebase 云消息传递

javascript - CoffeeScript 绑定(bind)变量

c - C 中的点或 "reset"变量

R:函数参数和 lapply 嵌套在函数中或使用 data.table 从外部函数调用

JavaScript 参数对象不具有所有参数