Exploring ES6

35
Exploring ES6

Transcript of Exploring ES6

Page 1: Exploring ES6

Exploring ES6

Page 2: Exploring ES6

Playground4 npm install babel-node

4 http://babeljs.io/repl

4 chrome://flags/#enable-javascript-harmony

4 Scratchpad in Firefox

Page 3: Exploring ES6

Favourite ES6 featureshttps://docs.google.com/forms/d/1bhmqePIstN9NNxK4QX1-F8XJcJ8C0HdPao01gAAoh3I/viewanalytics

-- Axel Rauschmayer

Page 4: Exploring ES6
Page 5: Exploring ES6

Begin from some sugar syntax

Page 6: Exploring ES6

4 Classes

4 Modules

4 Arrow functions

4 Template literal

4 Destructuring

Page 7: Exploring ES6

Classes// ES3var inherit = (function() { var F = function() {} return function(C, P) { F.prototype = P.prototype C.prototype = new F C.prototype.constructor = C }})()function Overlay(options) {}function Dialog(options) { Overlay.call(this, options)}inherit(Dialog, Overlay)

Page 8: Exploring ES6

Classes// ES5function Dialog(options) { Overlay.call(this, options)}Dialog.prototype = Object.create(Overlay.prototype)Dialog.prototype.constructor = Overlay

Page 9: Exploring ES6

Classes// ES6class Overlay { constructor(options) {}}class Dialog extends Overlay { constructor(options) { super(options) } open() {}}

Page 10: Exploring ES6

Classesmixin

import mixin from 'mixin'class Overlay { constructor(options) {}}class Dialog extends mixin(Overlay, EventEmitter) { constructor(options) { super(options) } open() {}}

Page 11: Exploring ES6

Classes// getter/setterclass Polygon { constructor(height, width) { this.height = height this.width = width }

get area() { return this.calcArea() }

calcArea() { return this.height * this.width }}

Page 12: Exploring ES6

Classes// static methodsclass Point { constructor(x, y) { this.x = x this.y = y }

static distance(a, b) { const dx = a.x - b.x const dy = a.y - b.y

return Math.sqrt(dx * dx + dy * dy) }}

Page 13: Exploring ES6

Modules// CommonJS// export// animationFrame.jsmodule.exports = { requestAnimationFrame: window.requestAnimationFrame, cancelAnimationFrame: window.cancelAnimationFrame}// importvar raf = require('./animationFrame').requestAnimationFrame

Page 14: Exploring ES6

Modules// es6// exportexport requestAnimationFrameexport cancelAnimationFrame// importimport { requestAnimationFrame as raf, cancelAnimationFrame as caf } from './animationFrame'

// exportexport default React// importimport React, { Component } from 'react'

Page 15: Exploring ES6

Arrow functions()=>{}

Identifier => Expression

// ES5var total = values.reduce(function (a, b) { return a + b;}, 0);

// ES6var total = values.reduce((a, b) => a + b, 0);

Page 16: Exploring ES6

Template4 multiple lines

4 expression inside

`Error Code: ${exception.code},Error Message: ${exception.message}`

Page 17: Exploring ES6

Destructuring// arrayvar [a, , b] = [1,2,3][a, b] = [b, a]// objectlet options = {closeOnPressingESC: false, closeOnClicking: true}let { closeOnPressingESC: esc, closeOnClicking: click } = options

Page 18: Exploring ES6

Setup4 npm init

4 npm install webpack babel-loader

4 touch webpack.config.js

Page 19: Exploring ES6

var webpack = require('webpack'), path = require('path')

module.exports = { entry: [ './src/index.js' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, module: { loaders: [{ loaders: ['babel'], include: path.join(__dirname, 'src') }] }}

Page 20: Exploring ES6

More

Page 21: Exploring ES6

4 Iterator

4 Generator

4 Proxy

Page 22: Exploring ES6

Iterator// for in (not recommended)for (var index in values) { console.log(values[index])}

// for offor (var value of values) { console.log(value)}

Page 23: Exploring ES6

IteratorArray, String, Map, Set, Array-like objects(NodeLists...)

Page 24: Exploring ES6

Iteratorclass RangeIterator { constructor(start, stop) { this.value = start this.stop = stop }

[Symbol.iterator]() { return this; }

next() { var value = this.value if (value < this.stop) { this.value++ return {done: false, value: value} } else { return {done: true, value: undefined} } }}function range(start, stop) { return new RangeIterator(start, stop)}

Page 25: Exploring ES6

Generatorfunction* range(start, stop) { for (var i = start; i < stop; i++) yield i}

Generators are iterators.All generators have a built-in implementation of .next() and Symbol.iterator.

Page 26: Exploring ES6

Generatorrequest('/api/user/~me', function(res) { request('/api/statuses/' + res.id, function(res) { // ... })})

Page 27: Exploring ES6

Generatorfunction fetch(url) { request(url, function(response){ it.next(response) })}

function *main() { var result1 = yield fetch('/api/user/~me') var result2 = yield request('/api/statuses/' + result1.id )}

var it = main()it.next()

Page 28: Exploring ES6

Generatorfunction runGenerator(g) { var it = g(), ret (function iterate(val){ ret = it.next( val )

if (!ret.done) { if ('then' in ret.value) { ret.value.then( iterate ) } else { setTimeout( function(){ iterate( ret.value ) }, 0 ) } } })()}

Page 29: Exploring ES6

GeneratorrunGenerator(function *main(){ var result1 = yield fetch('/api/user/~me') var result2 = yield fetch('/api/statuses/' + result1.id )})

https://github.com/tj/co

Page 30: Exploring ES6

Proxysetter/getter in ES5

// ES5var person = {}Object.defineProperty(person, 'age', { set: function(value) { if (value > 200) { throw new RangeError('seems invalid') } }})

Page 31: Exploring ES6

Proxysetter/getter, the different waylet validator = { set(obj, prop, value) { if (prop === 'age') { if (!Number.isInteger(value)) { throw new TypeError('The age is not an integer') } if (value > 200) { throw new RangeError('The age seems invalid') } }

// The default behavior to store the value obj[prop] = value }}

let person = new Proxy({}, validator)

Page 32: Exploring ES6

Proxynew Proxy(target, handler)

4 handler.getPrototypeOf()

4 handler.setPrototypeOf()

4 handler.isExtensible()

4 handler.preventExtensions()

4 handler.getOwnPropertyDescriptor()

Page 33: Exploring ES6

Proxy4 handler.defineProperty()

4 handler.has()

4 handler.get()

4 handler.set()

4 handler.deleteProperty()

4 handler.enumerate()

4 handler.ownKeys()

Page 34: Exploring ES6

Proxy4 handler.apply()

4 handler.construct()

Page 35: Exploring ES6

References

4 ES6 in depth

4 Learn ECMAScript 6 inside and out

4 Meta programming with ECMAScript 6 proxies