JavaScript的幾個概念摘錄。
阿新 • • 發佈:2018-12-29
ES201X是JavaScript的一個版本。
ES2015新的feature
新的宣告型別let, const,配合Block Scope。(if, forEach,)
之前:
var, Global scope和function scope。
之後:
let, const , 這2個型別宣告用在Block Scope內。
宣告一次還是多次?
let, const只能宣告一次。但var宣告可以反覆宣告:
const num = 5; const num = 7; // SyntaxError: identifier 'num' has already been declaredvar x = 2; // x = 2 var x = 4; // x = 4
const 用於不會改變的值。
⚠️const x = {} , 可以改變其內的屬性值,或增加新的key/value對兒。
這是因為,const variables當處理arrays 或objects時會改變,
技術上講,不是再分配一個新的值給它,而是僅僅改變內部的元素。
const farm = []; farm = ['rice', 'beans', 'maize'] // TypeError: Assignment to constant variable//但可以 farm.push('rice')
Hoisting
Declarations will be brought to the top of the execution of the scope!
⚠️ var x = "hello" 這種宣告加分配assign的寫法無法Hoisting!!
函式宣告也可以Hoisting.