Javascript函数参数参数或全局变量 [英] Javascript Function Parameter argument or global variable

查看:238
本文介绍了Javascript函数参数参数或全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var x=10;
function foo(){
    x=120;
    alert(arguments[0]); //outputs 10
}
foo(x);

如何知道函数中使用的x是参数还是全局变量?在代码中

How can I know whether the x I'm using within function is an argument or global variable?In the code

如果我提供了它

function foo(x){
    x=120;
    console.log(arguments[0]);//logs 120
}
foo(x);

这两个代码之间有什么区别,幕后发生了什么以及参数数组如何变化?

What is the difference between these two code, what is happening behind the scene and how come arguments array changed?

推荐答案

我怎么知道函数中使用的x是参数 还是全局变量?

How can i know whether the x i m using within function is an argument or global variable?

通过检查函数的参数列表.如果它像这样提到参数x:

By inspecting the parameter list of your function. If it mentions a parameter x like this:

function foo(x) {

然后您知道x是一个参数.它是arguments[0]的别名(别名),因为它是第一个参数. arguments对象不是真正的数组.它具有名称为数字的属性,并且具有length属性,因此它看起来类似于数组,但是缺少数组的其他功能.

then you know that x is a parameter. It is an alias (another name) for arguments[0], because it is the first argument. The arguments object is not a real array. It has properties whose names are numbers, and it has a length property, so it seems to resemble an array, but it lacks the other features of an array.

您可以将arguments视为函数调用中传递的值的最终存储.参数名称是获取存储在arguments中的值的便捷方法.

You can think of arguments as the definitive storage for the values passed in the function call. The parameter names are a convenient way to get at the values stored in arguments.

如果您的功能开始:

function foo() {

然后它没有参数.您在函数内引用的任何内容都必须是通过另一种方式定义的值.它可能是在函数内部声明的局部变量:

then it has no parameters. Anything you refer to inside the function must be a value defined another way. It could be a local variable declared inside the function:

function foo() {
    var x = 10;

或者它可以引用在函数外部声明的名称:

Or it could refer to a name declared outside your function:

var x;

function foo() {
    x = 10;

在没有严格模式"的JavaScript中,可以这样说:

In JavaScript without "strict mode", it was possible to say:

function foo() {
    x = 10;

,无需在任何地方声明var x.结果是x将被创建为全局变量(或全局对象的属性,例如,在浏览器中将创建window.x).这是大量的bug,因为您可能会拼写变量名而不会注意到您给一个不存在的变量赋值.

without ever declaring var x anywhere. The result would be that x would be created as a global variable (or property of the global object, e.g. in the browser it would create window.x) This was a big source of bugs because you could misspell a variable name and not notice you were assigning a value to a non-existent variable.

这篇关于Javascript函数参数参数或全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆