<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>第一种场景</title>
<script type="text/javascript">
-----------------------------------------------------------------
var a = 1;
function fn1(){
alert(a); //1
}
fn1();
var a = 1;
function fn1(){
alert(a); //undefined
if (false) {
var a = 3;
};
}
fn1();
-------------------------------------------------------------------
var a = 1;
function fn1(){
alert(a); //undefined
if (false) {
//函数执行的时候,即使这部分代码没有执行,会创建局部的var time=未定义,所以未定义,函数体中没有通过var声明的变量,会加入到全局window作用域中
var a = 2;
function fun() {//函数要执行才加入局部作用域
console.log("I am inside!");
};
};
fun();//fun is not a function,变为true就是I am inside!
}
fn1();
-------------------------------------------------------------------
var a = 1;
function fn1(){
alert(a); //undefined
if (true) {
var a = 2;
function fun() {//函数要执行才加入局部作用域
console.log("I am inside!");
};
};
fun();//I am inside!
}
fn1();
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>第一种场景</title>
<script type="text/javascript">
var string = "Hello World!";
for (var i = 0; i < string.length; i++) {
console.log(string[i]);//H e l l o W o r l d !
};
console.log("循环结束");
console.log(i); //12
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>块级作用域</title>
<script src="../../../vendor/traceur.js"></script>
<script src="../../../vendor/bootstrap.js"></script>
<script type="text/javascript">
console.log("ES5:");
function fun() {
var num = 100;
if (true) {
var num = 200;
};
console.log(num);
};
fun(); //200
</script>
<script type="text/traceur">
console.log("ES6:");
function fun() {
let num = 100;
if (true) {
let num = 200;
console.log(num);//200
};
console.log(num);//100
};
fun(); //100
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>立即执行函数</title>
<script src="../../../vendor/traceur.js"></script>
<script src="../../../vendor/bootstrap.js"></script>
<script type="text/javascript">
console.log("ES5:");
function fun() {
console.log("I am outside!");
};
(function () {
function fun() {
console.log("I am inside!");
};
fun();//I am inside!
}());
fun();//I am outside!
(function () {
if (false) {//函数不加入局部作用域
function fun() {
console.log("I am inside!");
};
};
fun();// fun is not a function
}());
fun();//I am outside!
(function () {
if (true) {//加入局部作用域
function fun() {
console.log("I am inside!");
};
};
fun();// I am inside!
}());
fun();//I am outside!
</script>
<script type="text/traceur">
console.log("ES6:");
function fun() {
console.log("I am outside!");
};
(function () {
if (false) {
function fun() {//只在大括号范围内有效。es6块级作用域
console.log("I am inside!");
};
};
fun();//I am outside!
}());
fun();//I am outside!
</script>
</head>
<body>
</body>
</html>