在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代碼。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM