12. ModulesModules
// lib/math.js
export function sum (x, y) { return x + y }
export var pi = 3.141593
// someApp.js
import * as math from "lib/math"
console.log("2π = " + math.sum(math.pi, math.pi))
// otherApp.js
import { sum, pi } from "lib/math"
console.log("2π = " + sum(pi, pi))
13. Spread OperatorSpread Operator
var params = [ "hello", true, 7 ]
var other = [ 1, 2, ...params ] // [ 1, 2, "hello", true, 7 ]
//Function with Rest Parameter
function f (x, y, ...a) {
return (x + y) * a.length
}
f(1, 2, ...params) === 9
var str = "foo"
var chars = [ ...str ] // [ "f", "o", "o" ]
17. GeneratorsGenerators
function* foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}
var it = foo( 5 );
console.log( it.next() ); // { value:6, done:false }
console.log( it.next( 12 ) ); // { value:8, done:false }
console.log( it.next( 13 ) ); // { value:42, done:true }
18. CoroutinesCoroutines
'use strict'
const co = require('co');
const marked = require('marked');
const fs = require('fs-promise');
const handlebars = require('handlebars');
co(function *() {
let md = yield fs.readFile('README.md');
let html = marked(md.toString());
let template = yield fs.readFile('layout.hbs');
let output = handlebars.compile(template.toString())({
title: 'README',
contents: html
});
yield fs.writeFile('index.html', output);
}).catch(function(err) {
console.error(err.stack);
});
19. Default parameter valueDefault parameter value
function f (x, y = 7, z = 42) {
return x + y + z
}
f(1) === 50
//ECMAScript 5
function f (x, y, z) {
y = y || 7;
if (z === undefined){
z = 42;
}
return x + y + z;
};
f(1) === 50;
20. String templateString template
var customer = { name: "Foo" };
var card = { amount: 7, product: "Bar", unitprice: 42 };
var message = `Hello ${customer.name},
want to buy ${card.amount} ${card.product} for
a total of ${card.amount * card.unitprice} bucks?`;
21. Property & method shorthandProperty & method shorthand
var x = 10;
var y = "eita";
var obj = { x, y };// { x: 10, y: "eita" }
let otherObj = {
foo (a, b) {
…
},
bar (x, y) {
…
},
*quux (x, y) {
…
}
};