简体   繁体   English

函数变量和函数变量具有相同的名称。 如何进入?

[英]function variable and in function variable have the same name. How to access?

I was wondering how does javascript(if possible) access a variable that has the same name as the variable input of the function. 我想知道javascript(如果可能)如何访问与该函数的变量输入同名的变量。

function myfunc(var1)
{
    var var1 = "World";
    alert(var1);
}

How can I tell the function which var1 to print? 我怎样才能告诉函数要打印哪个var1?

That doesn't actually define a second variable with the same name. 那实际上并没有定义具有相同名称的第二个变量。 Even with the var statement you are just overwriting the function parameter of the same name. 即使使用var语句,您也只会覆盖相同名称的function参数。

Just give your second variable a unique name. 只需给您的第二个变量一个唯一的名称即可。

(By the way, even if this actually worked it would still be a bad idea because it would make your code hard to read.) (顺便说一句,即使这确实可行,也仍然不是一个主意,因为这会使您的代码难以阅读。)

nnnnnn is correct, I tested it. nnnnnn是正确的,我测试了它。 Arguments that are passed to a function can be accessed in 2 ways, by their parameter name and through the arguments variable. 传递给函数的参数可以通过其参数名称和arguments变量两种方式访问​​。 arguments[0] would be the value of the first parameter. arguments[0]将是第一个参数的值。

In the example below you would expect 2 alerts, the first one saying "Hello" and the second saying "World" . 在下面的示例中,您会期望收到2条警报,第一个警报说"Hello" ,第二个警报说"World" But they both say "World" proving that assigning var1 actually changes the value of the argument being passed to the function. 但是他们俩都说"World"证明分配var1实际上改变了传递给函数的参数的值。

function myfunc(var1) {
    var var1 = "World";
    alert(arguments[0]);
    alert(var1);
}

myfunc("Hello");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 函数使用两个参数:变量和具有相同名称的字符串。 将它们减少为一个参数? - A function uses two parameters: a variable and a string with the same name. Reduce them to one parameter? 如何在 JavaScript 中具有相同的变量和函数名称 - How it's possible to have same variable and function name in JavaScript 如何在javascript中访问函数内的相同变量名 - How to access same variable name inside function in javascript 同名的函数和变量 - Function and variable with the same name 如何仅使用变量名访问变量并使用 function 调用语法为同一变量设置值? - How to access a variable using just variable name and set a value for the same variable using function call syntax? 当变量和函数具有相同名称时,引用是什么? - What will the reference be when a variable and function have the same name? 名称与Node.js中的参数名称相同时,如何从函数访问全局变量? - How to access global variable from a function when the name is same as argument name in Node.js? 具有相同名称的变量和函数 - variable and function with same name clobbering 在具有相同名称的变量的子函数中访问父函数的变量 - access parent function's variable inside child function having variable with same name 我可以将函数名称作为数组变量吗? - Can I have a function name be an array variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM