首页 > JavaScript 加var 关键字与不加var关键字有啥区别呢?

JavaScript 加var 关键字与不加var关键字有啥区别呢?

貌似加var不加都可以,但这两个有啥区别呢?


1.在函数作用域内 加var定义的变量是局部变量,不加var定义的就成了全局变量。
使用var定义

var a = 'hello World';
function bb(){
    var a = 'hello Bill';
    console.log(a);   
}
bb()   // 'hello Bill'
console.log(a);    // 'hello world'

不使用var定义

var e = 'hello world';
function cc(){
    e = 'hello Bill';
    console.log(e);    // 'hello Bill'
}
cc()   // 'hello Bill'
console.log(e)     // 'hello Bill'

2.在全局作用域下,使用var定义的变量不可以delete,没有var 定义的变量可以delete.也就说明隐含全局变量严格来说不是真正的变量,而是全局对象的属性,因为属性可以通过delete删除,而变量不可以。

3.使用var 定义变量还会提升变量声明,即
使用var定义:

function hh(){
    console.log(a);
    var a = 'hello world';
}
hh()    //undefined

不使用var定义:

function hh(){
    console.log(a);
    a = 'hello world';
}
hh()    // 'a is not defined'

这就是使用var定义的变量的声明提前。

4.在ES5'use strict'模式下,如果变量没有使用var定义,就会报错


简单来说就是加了var是局部变量 不加是全局变量。只有加了var的情况下就能限定该变量的使用范围 这样在别的方法里面也可以命名同样的变量了


  1. declared variables are constrained in the execution context in which they are declared, undeclared variables are always global

  2. declared variables are created before any code is executed, whereas undeclared variables do not exist until the code assigning to them is executed

  3. declared variables are a non-configurable property of their execution context (function or global), undeclared variables are configurable (e.g. can be deleted)

declared variables 即你题目中加了 var 关键字的变量

【热门文章】
【热门文章】