<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript中变量和变量作用域知识点</title>
<script type="text/javascript">
/*
查阅相关文档之后才知道,打印undefined说明该变量已经声明,但没有赋值;打
印age is not defined说明该变量连声明都没有。通过这条结论说明,window.xx的形式会在window对
象中隐式的声明该变量
*/
console.log(window.age); //结果为undefined
// console.log(age); //报错ReferenceError: age is not defined
//这也说明了,为什么以下代码可以直接运行了
window.hometown = '江西省赣州市于都县';
window.a = 666;
console.log(window.hometown, window.a); //结果为江西省赣州市于都县 666
console.log(hometown, a); //结果为江西省赣州市于都县 666
/*
JavaScript的运行阶段,分为词法分析阶段和运行阶段,在词法分析阶段时,先声
明了str变量但没有赋值,所以在运行阶段就出现了undefined
*/
function fn1() {
console.log(str); //结果为undefined
var str = '江西省于都县';
}
fn1();
/*
以上代码类似于下面的代码
function fn1() {
var str; //变量声明提升
console.log(str); //所以结果为undefined
str = '江西省于都县';//变量赋值不会提升
}
fn1();
*/
/*
词法分析阶段也无法声明str2,因为没有var关键字声明,所以在运行阶段直接报错
*/
// function fn2() {
// console.log(str2); //报错ReferenceError: str2 is not defined
// str2 = '赣南脐橙';
// }
// fn2();
console.log('**************');
function fn3(){
console.log(window.str3); //结果为undefined
str3 = '于都珠子粉';
}
fn3();
var str4 = 268;
function fn4(){
console.log(window.str4); //结果为268
console.log(str4); //结果为268
str4 = '于都酸萝卜';
console.log(window.str4, str4); //结果为于都酸萝卜 于都酸萝卜
}
fn4();
function fn5() {
//凡是没有使用var声明的变量,最终都会成为全局对象window的属性
str5 = '于都番薯干'; //没有使用var关键字声明的变量,该变量是全局变量
console.log(str5); //结果为于都番薯干
console.log(window.str5); //结果为于都番薯干
}
fn5();
//fn5()函数外,也可以访问到str5变量,因为str5变量是没有使用var关键字声明的变量,所以该变量是全局变量
console.log(str5); //结果为于都番薯干
console.log(window.str5); //结果为于都番薯干
</script>
</head>
<body style="background-color: #CCE8CF;">
<h3 style="color: #cd1636;">JavaScript中变量和变量作用域知识点</h3>
<a href="https://blog.csdn.net/czh500/article/details/103477355" target="_blank">
参考网页https://blog.csdn.net/czh500/article/details/103477355
</a>
<br/>
<a href="https://blog.csdn.net/sheldon178/article/details/48298151/" target="_blank">
参考网页https://blog.csdn.net/sheldon178/article/details/48298151/
</a>
<br/>
</body>
</html>