gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:22:12 24 4
gpt4 key购买 nike

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/

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