<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
/**
* 局部变量,函数内生效;函数外失效!(非要实现,研究闭包!)
*/
function aa(){
let x=1;
x=x+1;
console.log(x)
}
aa();
//x=x+1;
// console.log(x); // x is not defined!!
function bb(){
let x='A';
x=x+2;
console.log(x) // A2
}
bb();
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
'use strict';
/**
* 内部函数可以引用外部函数变量;反之不可!!
*/
function father(){
let x=1;
function son(){
let y=x+1;
console.log(y) //2
}
son();
let z=y+1; // y is not defined
console.log(z);
}
father();
</script>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
'use strict';
function aa(){
let x=1;
function bb(){
let x=2;
console.log("inner",x);
}
bb();
console.log("outer",x);
}
aa();
/** 从里到外找,若出现重名,则内部函数变量屏蔽外部函数变量
* inner 2
outer 1
*/
</script>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
'use strict';
/**
* 提升变量作用域
*/
// function aa() {
// let x='x'+y;
// console.log(x)
// let y='y'
// }
// aa() //Uncaught ReferenceError: Cannot access 'y' before initialization
/**
* js执行引擎自动提升了y的申明,但是不会提升y的赋值!!
*/
function bb(){
let y;
let x='x'+y;
console.log(x)
y='y';
}
bb(); // xundefined
// * 因此需要养成规范:所有变量定义放在函数头部!!!
function cc(){
let x=1,y=2,
z=x+y,
s,d,f; //undefined
}
</script>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
// var x="aaa" // 全局变量默认绑定在window对象下
// alert(x)
// alert(window.x)
// window.alert(window.x) //alert()函数本身也是window对象的一个变量
// // 以上效果一样
//
var msg="hello"
var old=window.alert;
old(msg)
window.alert=function (){ //alert()函数本身也是window对象的一个变量
}
// window.alert(msg) //alert失效
window.alert=old;
window.alert(msg) // alert恢复效果
</script>
<body>
</body>
</html>