一般 Function
function calculateBMI(hight, mass) {
return mass/(hight*hight);
}
console.log(calculateBMI(1.7,70 ))
解析 Statements and Expressions
Function Statements
不回傳任何的值,在程式執行的最開始,就會透過 hoisting 先被儲存在記憶體中,以下程式碼不報錯
Function name : run
Function process : console.log('run')
// call the fuction before declare, but it already hoisted in memory
run(); // log text 'run'
function run() {
console.log('run');
}
Function Expressions
將 Function表達式的值存在變數 doRun 中,也稱作匿名函式(anonymous function 或 function literal)
在程式執行的最開始,指儲存變數名,不儲存程式碼 -> 以下程式碼報錯
Function name : x
Function process : console.log('run')
// call the fuction before declare, and it is undefined (not a function)
run(); // log text 'run'
const doRun = run() {
console.run('run');
};
Javascript Hoisting
w3schools 解釋 :
Hoisting is JavaScript's default behavior of moving declarations to the top.
In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared.
-> 把宣告變數優先執行
run();
console.log(test);
var test = 'test';
function run(){
console.log('run')
}
結果:
run
undefined (在 JavaScript 中不等於報錯)
-> 在程式的一開始, 將變數都存在記憶體中了(但值尚未指定) -> test 為 undefined
宣告 : declaration
賦值 : initialization
Hoisting : start -> declaration(Hoisted) -> when excute the code(initialization)
新手練功中, 歡迎指教、點評~
課程 : https://www.udemy.com/course/the-complete-javascript-course/
來源 :
https://pjchender.blogspot.com/2016/03/javascriptfunction-statements-and.html
https://pjchender.blogspot.com/2015/12/javascript-hoisting.html
https://www.w3schools.com/js/js_hoisting.asp