480 重复声明

var a = 12;
var a = 13;
console.log(a); //  => 13


// --------------------------------------------------



let a = 12;
let a = 13; //  => Uncaught SyntaxError: Identifier 'a' has already been declared
console.log(a);


// --------------------------------------------------



/*
 * 全局作用域(栈内存)
 *   1.变量提升
 *   2.代码执行 
 */
console.log(1); //   => 这行代码就已经不会执行了
let a = 12;
console.log(a);
let a = 13;  //   => Uncaught SyntaxError: Identifier 'a' has already been declared
console.log(a);


// --------------------------------------------------


console.log(1); //  => 1
console.log(a); //  => Uncaught ReferenceError: Cannot access 'a' before initialization
let a = 12;


// --------------------------------------------------


//   => 所谓重复是:不管之前通过什么办法,只要当前栈内存中存在了这个变量,我们使用let/const等重复再声明这个变量就是语法错误
console.log(a);
var a = 12;
let a = 13; //  => Uncaught SyntaxError: Identifier 'a' has already been declared
console.log(a);


// --------------------------------------------------


fn();
function fn(){ console.log(1); }
fn();
function fn(){ console.log(2); }
fn();
var fn = function(){ console.log(3); }
fn();
function fn(){ console.log(4); }
fn();
function fn(){ console.log(5); }
fn();


// --------------------------------------------------


// 补充的案例
// 打印结果说明fn提升到了var语句的前面。但是var 声明的fn怎么提升呢?我猜比function声明的函数fn的提升还要往上,提升到了function fn前面。如果是在后面,那执行第一个fn()的时候,就应该报fn不是函数的错误
console.log(fn) // ƒ fn() { console.log(5); }
fn(); // 5
console.log(fn) // ƒ fn() { console.log(5); }
// var fn = 111 // 改变fn的值为111
fn(); // Uncaught TypeError: fn is not a function
function fn() { console.log(1); }
fn();
function fn() { console.log(2); }
fn();
var fn = function () { console.log(3); }
fn();
var fn = 222
fn()
function fn() { console.log(4); }
fn();
function fn() { console.log(5); }
fn();


// --------------------------------------------------


// 补充的案例
console.log(fun) // 函数fun
console.log(a) // undefined
fun(); // undefined  90
var a = 100;
function fun() {
    // undefined,说明var声明的变量a提升在function声明的函数前,如果不是,则应该报错,找不到a
    console.log(a);  
    a = 90;
    console.log(a);    // 90
}
// fun(); //? ?
console.log(a); // 100

posted on 2020-06-25 21:03  冲啊!  阅读(105)  评论(0编辑  收藏  举报

导航