iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
0
Modern Web

用30天了解javascript系列 第 6

[用30天了解javascript]Day6.提升(Hoisting)

變數提升

console.log(name); //name is not defined

未宣告變數執行時,會出現錯誤

console.log(name); //undefined
var name = "John";

為何會undefined呢?

在執行程式碼前,會先將變數放到記憶體裡面,不會賦予值,所以會是undefined,一直到執行時,才會賦予值

在編譯器的解讀是

var name;
console.log(name); //執行
name = "John";

因此,只有宣告會提升,賦值(值指定給變數)不會提升

函式提升

hello(); //hello~
function hello(){
	console.log('hello~');
}

//建議寫法
function hello(){
	console.log('hello~');
}
hello();//hello~

執行程式碼前,會把函式陳述式整個放入記憶體,因此呼叫name();可直接被執行,但建議先定義好再去呼叫會比較好

hello(); //hello is not defined
console.log(hello); //undefined
var hello = function (){
	console.log('hello~');
}

在編譯器解讀

var hello;
hello = function (){ 
	console.log('hello~');
}
hello(); //hello~

因此,函式表達式不會被提升

重複宣告

函式與變數同名

函式會優先

var name = function(){
	console.log('variable name2');
}
function name(){
	console.log('function name');
}
name();//variable name2

在編譯器解讀

function name(){
	console.log('function name');
}
var name 
name = function(){
	console.log('variable name2');
}
name();//variable name2

多個函數名稱相同

會覆蓋前面的宣告

function name(){
	console.log('name1');
}
name(); //name2
function name(){
	console.log('name2');
}
name(); //name2

在編譯器解讀

function name(){
	console.log('name1');
}
function name(){
	console.log('name2');
}
name(); //name2
name(); //name2

上一篇
[用30天了解javascript]Day5.全域變數、區域變數
下一篇
[用30天了解javascript]Day7.運算子
系列文
用30天了解javascript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言