在JavaScript中声明变量时使用var和不使用var的区别

1、变量提升

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style></style>
    <script src="js/jquery.min.js"></script>
</head>
<body>
<script>
$(function(){
    // console.log(obj1); // undefined
    // console.log(obj2); // Uncaught ReferenceError: obj2 is not defined
        
    // console.log(obj1.name); // Uncaught TypeError: Cannot read property 'name' of undefined
    // obj1.hello(); // Uncaught TypeError: Cannot read property 'hello' of undefined
    // console.log(obj2.name); // Uncaught ReferenceError: obj2 is not defined
    // obj2.hello(); // Uncaught ReferenceError: obj2 is not defined
    var obj1 = {name:'zhangsan', hello:function(){console.log('hello, zhangsan.');}};
    obj2 = {name:'lisi', hello:function(){console.log('hello, lisi.');}};
        
    // console.log(obj1); // {name: "zhangsan", hello: ƒ}
    // console.log(obj2); // {name: "lisi", hello: ƒ}
    // console.log(obj1.name); // zhangsan
    // obj1.hello(); // hello, zhangsan.
    // console.log(obj2.name); // lisi
    // obj2.hello(); // hello, lisi.
});
</script>
</body>
</html>

在声明变量后,再访问该变量是没有问题的。这也证明了JavaScript代码是逐行执行的。

而在声明变量前访问该变量,除非该变量是用var声明的,否则都会报错。

事实上,下面的代码:

console.log(obj1);
var obj1 = {name:'zhangsan', hello:function(){console.log('hello, zhangsan.');}};

等价于

var obj1;
console.log(obj1);
obj1 = {name:'zhangsan', hello:function(){console.log('hello, zhangsan.');}};

2、发现问题

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style></style>
    <script src="js/jquery.min.js"></script>
</head>
<body>
<button onclick="obj1.hello()">obj1</button><!-- Uncaught ReferenceError: obj1 is not defined -->
<button onclick="obj2.hello()">obj2</button>
<script>
$(function(){
    var obj1 = {name:'zhangsan', hello:function(){console.log('hello, zhangsan.');}};
    obj2 = {name:'lisi', hello:function(){console.log('hello, lisi.');}};
});
</script>
</body>
</html>

这里点击按钮obj1报错了,而点击按钮obj2没有报错。

3、总结

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style></style>
    <script src="js/jquery.min.js"></script>
</head>
<body>
<button onclick="obj1.hello()">obj1</button>
<button onclick="obj2.hello()">obj2</button>
<script>
var obj1 = {name:'zhangsan', hello:function(){console.log('hello, zhangsan.');}};
$(function(){   
    obj2 = {name:'lisi', hello:function(){console.log('hello, lisi.');}};
});
</script>
</body>
</html>

这里把var obj1 = {/*...*/};写在$(function(){/*...*/});外面就好了。

如果在函数里面使用var声明变量,那么该变量就是局部变量,函数外面是不能访问该变量的(在函数里面却可以访问在函数外面声明的变量)。

如果在函数里面给一个变量赋值,且该变量没有使用var声明,那么该变量就是全局变量

提示:$(function(){/*...*/});等价于$(document).ready(function(){/*...*/});,它的作用是为了防止文档完成加载(准备就绪)之前运行任何jQuery代码。