Cheng-Han Wu
@jackymaxj
參考自
Introduction to ECMAScript 6
Christophe Coenraets
@ccoenraets
Cheng-Han Wu
Taipei, Taiwan
@jackymaxj
https://hackmd.io
https://github.com/jackycute
Modules 模組, Promises, Classes 類別, 等等
“不能讓網頁壞掉”
也就是說不能亂改 var 功能
轉譯器
函數內有效
function divide(x, y) { if (y !== 0) { var result; result = x / y; } return result; } console.log(divide(10, 2)); // 5
區塊內有效
function divide(x, y) { if (y !== 0) { let result; result = x / y; } return result; // throws Error } console.log(divide(10, 2));
區塊內有效
const PI = 3.14159265359; const COLOR = { name: "Red", hexValue: "#FF0000" };
不能重新給值或是重新定義
ECMAScript 5
var firstName = "Christophe"; var lastName = "Coenraets"; var twitterId = "@ccoenraets"; var speaker = { firstName: firstName, lastName: lastName, twitterId: twitterId };
ES6 Object Literals 物件字面
let firstName = "Christophe"; let lastName = "Coenraets"; let twitterId = "@ccoenraets"; let speaker = {firstName, lastName, twitterId};
用 var 也可以
使用語法來對應陣列或是物件結構的字面
進而從中抽離資料
ECMAScript 5
var colors = ["red", "green", "blue"]; var primary = colors[0]; var secondary = colors[1]; var tertiary = colors[2]; console.log(primary); // red console.log(secondary); // green console.log(tertiary); // blue
var colors = ["red", "green", "blue", "yellow", "orange"]; var [primary, secondary, ...otherColors] = colors; console.log(primary); // red console.log(secondary); // green console.log(otherColors); // [ 'blue', 'yellow', 'orange']
function getDate() { var d = new Date(); return [d.getDate(), d.getMonth() + 1, d.getFullYear()]; } var [day, month, year] = getDate(); console.log(day); // 4 console.log(month); // 5 console.log(year); // 2015
ECMAScript 5
var speaker = { firstName: "Christophe", lastName: "Coenraets", twitterId: "@ccoenraets" }; var firstName = speaker.firstName; var lastName = speaker.lastName; var twitterId = speaker.twitterId; console.log(firstName); // Christophe console.log(lastName); // Coenraets console.log(twitterId); // @ccoenraets
ES6 Object Destructuring 物件解構
var speaker = { firstName: "Christophe", lastName: "Coenraets", twitterId: "@ccoenraets" }; var {firstName, lastName, twitterId} = speaker; console.log(firstName); // Christophe console.log(lastName); // Coenraets console.log(twitterId); // @ccoenraets
var {fName: firstName, lName: lastName, twId:twitterId} = speaker; console.log(fName); // Christophe
ES5 Function
var greeting = function(message, name) { return message + ' ' + name; } console.log(greeting('Hello', 'Christophe'));
ES6 Arrow Function
var greeting = (message, name) => { return message + ' ' + name; }
var greeting = (message, name) => message + ' ' + name;
var greeting = name => 'Hello ' + name;
再一個範例
var array = [1, 2, 3]; var total = 0; array.forEach(function(item) { total = total + item; }); console.log(total);
var array = [1, 2, 3]; var total = 0; array.forEach(item => total = total + item); console.log(total);
ECMAScript 5
“var self = this” 也就是 “var that = this”
var obj = { init: function () { var self = this; setTimeout(function() { self.doSomething(); }, 1000); }, doSomething: function() { console.log("doing something in ES5"); } }; obj.init();
ES 6 Arrow Functions
真正的 “this”
var obj = { init: function() { setTimeout(() => this.doSomething(), 1000); }, doSomething: function() { console.log("doing something in ES6"); } }; obj.init();
Default Params 預設參數
var greeting = (name, msg="Hello") => msg + ' ' + name; console.log(greeting('Christophe', 'Hi')); // Hi Christophe console.log(greeting('Christophe')); // Hello Christophe
"function" 也可以用:
function greeting(name, message="Hello") { return message + ' ' + name; }
step1(function (value1) { step2(value1, function(value2) { step3(value2, function(value3) { step4(value3, function(value4) { // Do something with value4 }); }); }); });
尚未可用的值之代理者
➝ 清楚的輸入參數與回傳值的語意
定義
function step1() { var deferred = Q.defer(); FS.readFile("foo.txt", "utf-8", function (error, text) { if (error) { deferred.reject(new Error(error)); } else { deferred.resolve(text); } }); return deferred.promise; }
使用
Q.fcall(step1) .then(step2) .then(step3) .then(step4) .then(function(value4) { // Do something with value4 }) .catch(function(error) { // Handle any error from all above steps }) .done();
請把 *then(handler)* 想成 *addEventListener("done", handler)*
定義
function getList() { var deferred = $.Deferred(); if (list) { deferred.resolve(list); } else { deferred.reject("no list"); } return deferred.promise(); }
使用
service.getList() .done(function(list) { console.log(list); }) .fail(function(error) { console.log(error); });
定義
function timeout(millis) { var promise = new Promise(function (resolve, reject) { setTimeout(function() { resolve(); }, millis); }); return promise; }
使用
timeout(1000).then(function() { console.log('done waiting'); });
Promisified setTimeout()
定義 假資料服務 (Service)
var employees; function findAll() { return new Promise(function (resolve, reject) { if (employees) { resolve(employees); } else { reject("employees is not defined"); } }); }
使用 假資料服務 (Service)
findAll() .then(function(employees) { console.log(employees); }) .catch(function(error) { console.log(error); });
define(function (require) { var $ = require('jquery'); var findAll = function() { // implementation }; var findById = function(id) { // implementation }; return { findAll: findAll, findById: findById }; });
Common.js 模組
var findAll = function () { // implementation }; var findById = function(id) { // implementation }; module.exports = { findAll: findAll, findById: findById };
定義
// datelib.js export const today = new Date(); export var shortDate = function() { return today.getMonth() + 1 + '/' + today.getDate() + '/' + today.getFullYear(); }
使用
import {today, shortDate} from './datelib'; console.log(today); // Mon May 4 2015 11:04:06... console.log(shortDate()); // 5/4/2015 import * as date from "./datelib"; console.log(date.today); console.log(date.shortDate());
定義 假資料 (Service)
export function findAll() { // implementation } export function findById(id) { // implementation } export var endpoint = "http://localhost:5000";
使用 假資料 (Service)
import * as employeeService from "employee"; employeeService.findAll().then(function(employees) { console.log(employees); });
class Mortgage { constructor(amount, years, rate) { this.amount = amount; this.years = years; this.rate = rate; } calculate() { // No interest mortgage for ES6 fans return this.amount / (this.years * 12); } } let m = new Mortgage(200000, 30, 3); console.log(m.calculate());
class Circle extends Shape { constructor(x, y, radius) { super(x, y); this.radius = radius; } static get pi() { return 3.14159265359; } get circumference() { return 2 * Circle.pi * this.radius; } render() { console.log('Rendering circle'); } }
var c = new Circle(0, 0, 10); console.log(c.x); // 0 c.x = 5; console.log(c.x); // 5 console.log(Circle.pi); // 3.14159265359 console.log(c.circumference); // 62.8318530718 c.render(); // Rendering circle
var str = `Hello World!` console.log(str);
var multiLine = `This is an example of a multiline string`; console.log(multiLine);
var name = "Christophe"; console.log(`Hello, ${name}!`);
var user = {firstName: "Lisa", lastName: "Wong"}; console.log(`Hello, ${user.firstName} ${user.lastName}!`);
console.log(`Today is ${new Date()}!`);
var price = 100; var exchangeRate = 0.89; console.log(`Price in Euro: ${price * exchangeRate}`);
console.log(`Hello, ${user.firstName} ${user.lastName}! Today is ${new Date()}`);
function* idMaker(){ var index = 0; while(index < 3) { yield index++; } } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // undefined
var settings = {}; settings.server = "http://localhost"; settings.userName = "Christophe"; settings["language"] = "EN";
鍵必須是字串
var map = new Map(); map.set("server", "http://localhost"); map.set("userName", "Christophe"); map.get("userName"); map.has("userName"); map.delete("userName");
鍵可以是任何東西
有排序的不重複隨意值
var colors = new Set(); colors.add("red"); colors.add("blue"); console.log(colors.size); // 2; console.log(colors.has("red")); // true; colors.delete("red");