JS 定义变量方式

2017-03-24  本文已影响0人  快乐的大鹅
var
    var a = 1;
    var b;
    var c = 2;
    console.log(a);//1
    console.log(b);//undefined
    console.log(c);//2
    var c = 3 ;
    console.log(c);//3
    c = 4;
    console.log(c);//4
    k();
    function k(){
        var c = 5;
        console.log(c);//5
        c = 6;
        console.log(c);//6
    }
    console.log(c);//4
    m();
    function m(){
        c = 7;
    }
    console.log(c);//7
let
    let a = 1;
    let b;
    let c = 2;
    console.log(a);//1
    console.log(b);//undefined
    console.log(c);//2
    let c = 3 ;//SyntaxError: Identifier 'c' has already been declared
    c = 4;
    console.log(c);//4
    k();
    function k(){
        var c = 5;
        console.log(c);//5
        c = 6;
        console.log(c);//6
    }
    console.log(c);//4
const
    const a = 1;
    const b;//SyntaxError: missing = in const declaration
    const c = 2;
    console.log(a);//1
    console.log(c);//2
    const c = 3 ;//SyntaxError: redeclaration of const c
    c = 4;//TypeError: invalid assignment to const `c'
    k();
    function k(){
        const c = 5;
        console.log(c);//5
    }
    console.log(c);//2

20170506补充

console.log(f);//ReferenceError: f is not defined

没有定义变量直接使用会报错
ReferenceError: f is not defined

console.log(f);//undefined
var f;

变量在使用之后才被定义 对于var来说 会发生变量提升
不会报错而是报没有定义
undefined

console.log(f);//ReferenceError: can't access lexical declaration `f' before initialization
let f;

而对于let的情况 回直接报错
ReferenceError: can't access lexical declaration `f' before initialization

上一篇 下一篇

猜你喜欢

热点阅读