JavaScript函数参数和范围 [英] JavaScript function parameter and scope

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

问题描述

我已经使用下面列出的代码进行了一些测试:

I have done some tests with codes listed below:

function foo(x) {
    alert(y);
}
var y = 'I am defined outside foo definition';
foo();

上面的代码给了我一个警报我在foo定义之外定义".

The above code gives me an alert 'I am defined outside foo definition'.

然后进行另一项测试:

function bar(x) {
    alert(x);
}
var x = 'I am defined outside foo definition';
bar();

function bar(x) {
    alert(x);
}
x = 'I am defined outside bar definition';
bar();

以上两种代码都给我一个警报未定义".

Both the above codes give me an alert 'undefined'.

那为什么呢?

推荐答案

这是因为在声明参数x时

This is because when you declare the parameter x

function bar(x) {...}

您正在隐藏"全局变量x.您只能访问参数x

You are "hiding" the global variable x. You only have access to the parameter x

尝试传递全局x

function bar(x) {alert(x);}
var x = 'I am defined outside bar definition';
bar(x); // here the x is the global x that we pass in
        // the function gets a reference to the global x

如果省略该参数,则全局x将再次变为可见状态

If we omit the parameter then the global x would become visible again

function baz() {alert(x); }
var x = 'global var';
baz(); // 'global var'

请注意,良好的js应用程序中应限制全局变量.

Note that global variables should be limited in good js applications.

这篇关于JavaScript函数参数和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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