一次說清楚 JavaScript 中宣告的各種提升行為(var、function、let/const)

提升(Hoisting)是 JavaScript 宣告變數後執行的行為,然而在不同狀況下會有不同的提升行為,我們在這篇文章一併釐清,並在後頭做比較。

序言

大綱

摘要

Photo by Emily Morter on Unsplash

var 宣告與提升

(function(){
console.log(variable);
var variable=20;
}())
(function(){
var variable;
console.log(variable);
variable = 20;
}())
function parent(){
var name= 'Harry';
function child(){
var fullname = name + ' ' + 'Potter';
console.log(fullname);
}
return child
}
var child = parent();
child();// Harry Potter
function parent(){
var name= 'Harry';
function child(){
var fullname = name + ' ' + 'Potter';
console.log(fullname);
//幾百行之後
var name = 'Dennis';
}
return child
}
var child = parent();
child();// undefined Potter
function (){
var name='Dio' ,stand='Zawarudo',blabla='foo';
// below is your code;
}

function 宣告與提升行為

{
function test(){
console.log('callable');
}
}
test() //callable
greeting('Andy');function greeting(name){
console.log('Hello! ',name)
}
greeting2('Andy');var greeting2 = function(name){
console.log('Hello! ',name)
}
var greeting2;//這時 greeting2 是undefined greeting2('Andy');
greeting2 = function(name){
console.log('Hello! ',name)
}

ES6 的 let 與 const 宣告與提升行為

{ 
//Block scope
console.log(variable);
let variable = 20;
}
function parent(){
var name = 'Harry';
function child(){
var fullname = name + ' ' + 'Potter';
console.log(fullname);
// 幾百行之後
let name = 'Dennis';
}
return child;
}
var child = parent();
child();
Photo by Hermes Rivera on Unsplash

結論

寫在文末

If any interest, 👉 https://realdennis.me.

If any interest, 👉 https://realdennis.me.