3 个回答

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 关键字的变量

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题