JavaScript 函数中的局部和全局变量 [英] Local and global variables inside a JavaScript function

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

问题描述

我正在学习 JavaScript 全局和局部变量,但我对这个特定函数感到困惑.

I am learning JavaScript global and local variables, but I am confused on this particular function.

var text = "top";
function print() {
    return (text);
}
print();
// Returns 'top'

我明白为什么它返回顶部.var text 是一个全局变量.print() 函数可以访问它并返回text,从而返回'top'.

I understands why it returns top. var text is a global variable. print() function has access to it and returns text, thus returning 'top'.

var text = "top";
function print() {
    return (text);
    var text = "bottom";
}
print();
// Returns undefined

我对全局和局部变量有基本的了解(或者我是这么认为的).我知道函数 print 可以访问它自己的局部变量和全局变量.

I have a basic knowledge of global and local variables (or so I thought). I know that the function print has access to its own local plus global variables.

我不明白为什么这会返回 undefined.据我了解,行 return text; 检索全局变量 text,它可以访问(如第一个代码块所示).返回text = 'top'后,还声明了自己的同名值不同的局部变量,'bottom'.据我所知,局部变量 bottom 应该放在那里,因为它之前没有被调用.

I don't understand why this returns undefined. To my understanding, the line return text; retrieves global variable text, which it has access to (as shown on the first code block). After returning text = 'top', it also declares its own local variable with the same name but different value, 'bottom'. The local variable bottom, to my knowledge, ought to sit there because it wasn't called earlier.

为什么不显示top(甚至显示bottom),而是显示undefined?

Why didn't it show top (or even shows bottom), but instead shows undefined?

推荐答案

JavaScript hoists 您的变量声明,以便您的代码在功能上如下:

JavaScript hoists your variable declaration such that your code is functionally the following:

var text = "top";
function print() {
    var text;
    return (text);
    // Unreachable code below
    text = "bottom";
}
print();
// Returns undefined

因为在您的函数中声明的 text 在您点击 return(text)text="bottom" 时尚未定义code> 无法访问,print() 返回 undefined.

Since text, as declared in your function, is not yet defined when you hit return(text), and text="bottom" is unreachable, print() returns undefined.

参见JavaScript 中变量的范围是什么? 了解更多.此问题与案例 7 相关.

See What is the scope of variables in JavaScript? for more. This question relates to case 7.

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

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