JavaScript 加var 关键字与不加var关键字有啥区别呢?
高洛峰
高洛峰 2017-04-10 14:30:53
[JavaScript讨论组]

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(3)
PHP中文网

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号