VARIABLE
ES5所寫之 var 變數宣告,無論寫在哪裡,總是在一開始執行時被初始化:1 2 3 4 5 6 | console.log(a); //undefined console.log(b); //undefined var a = 10; function xx(){ var b = 10; } |
可以注意到的是 a,b 都有變成 undefined,表示有被註冊。
而 let 的差別在於在執行到 let 之前,變數絕對不會先被初始化。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | console.log(a); //undefined console.log(b); //undefined console.log(c); //ERROR!! var a = 10; function xx(){ var b = 10; let c = 19; console.log(c); //10 } console.log(a); //undefined console.log(b); //undefined console.log(c); //ERROR |
另外一個是 const, 被宣告之後的值不會被變動,適合用來宣告引用模組的 require,而且 const 固定之後,可以省下系統效能來追蹤變數值。
1 2 3 | const express = require( 'express' ); express = require( 'bodyParser' ); //ERROR! |
1 |
FUNCTION
Function 在 ES6 的寫法有以下幾種:1 2 3 4 5 6 7 8 9 10 11 12 13 | { //直接用 { } 代替 (function(){ })() console.log( 'hello world' ); } let some_object = { say(){ //不需要加 say : function (){} console.log( "Say: " ); }, hello(){ console.log( "Hell world!" ); } } |
STRING
字串在 ES6 之後有了新的寫法,感覺應該叫做模板 (格式化)吧,可以說是進階版的 printf。1 2 | let name = "canta y no llores." ; console.log(`Ay, ay, ay, ay, ${name}`); |
LAMBDA (Arrow Function)
1 2 3 4 5 6 7 8 9 10 | let func = (a,b) => a+b; //箭號後面的值會直接回傳。 console.log(func(1,2)); //3 func = (a,b) => { ++a; return a + b; } console.log(func(1,2)); //4 |
FOR OF LOOP
除了 for in 打印迭代順序外,for of 可以打印其值出來:1 2 3 4 | let array = [ "Ay" , "ay" , "ay" , "ay" , "canta y no llores" ]; for (let v of array){ console.log(v + "," ); } |
Symbol
symbol 可以用來辨識 ID, 在 ES6 中成為基本型別。 這個 id 可以用來當作監聽識別 ID 或辨識身分,1 2 3 4 | const test = Symbol( "BIG_EVENT" ); window.addListener(test, function (d){ }); |
解構
這裡的解構不是解構子,而是解構一個 object 物件,可以複製特定值指派到你想要的值中:1 2 3 4 5 6 7 8 9 | let { name : name, //後面這個 name 不是這裡的 name age : age, id : id, } = { name: "Stockholm" , age: 14, id: "test" } console.log(name); // Stockholm console.log(age); // 14 console.log(id); // test |
Reference:
https://github.com/getify/You-Dont-Know-JS