Muutettu viimeksi 26.11.2018 / Sivu luotu 30.11.2015
ECMAScript 6 esitteli joukon tärkeitä uutuuksia, jotka moni selain on tuntenut jo pitkään. Kaikki eivät vieläkään.
Sivun esimerkit perustuvat perustuvat laajaan ja perusteelliseen lähteeseen ECMAScript 6 – New Features: Overview & Comparison. (Monia näistä ja ehkä muitakin uutuuksia on esintynyt jo aiemmissakin luvuissa.)
var evens = [2,4,6,8,10,12,14] odds = evens.map(function (v) { return v + 1; }); pairs = evens.map(function (v) { return [v, v + 1]; }); write(odds) // 3,5,7,9,11,13,15 write(pairs) // 2,3,4,5,6,7,8,9,10,11,12,13,14,15
var evens = [2,4,6,8,10,12,14] odds = evens.map(v => v + 1) pairs = evens.map(v => ([v, v + 1])) write(odds) // 3,5,7,9,11,13,15 write(pairs) // 2,3,4,5,6,7,8,9,10,11,12,13,14,15
function f (x, y, z) { if (y === undefined) y = 7; if (z === undefined) z = 42; return x + y + z; }; write(f(1)) // 50
function f (x, y = 7, z = 42) { return x + y + z } write(f(1)) // 50
function f (x, y) { var a = Array.prototype.slice.call(arguments, 2); return (x + y) * a.length; }; write(f(1, 2, "hello", true, 7)) // 9
function f (x, y, ...a) { return (x + y) * a.length } write(f(1, 2, "hello", true, 7)) // 9
var Shape = function (id, x, y) { this.id = id; this.move(x, y); }; Shape.prototype.move = function (x, y) { this.x = x; this.y = y; };
class Shape { constructor (id, x, y) { this.id = id this.move(x, y) } move (x, y) { this.x = x this.y = y } }
var Rectangle = function (id, x, y, width, height) { Shape.call(this, id, x, y); this.width = width; this.height = height; }; Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; var Circle = function (id, x, y, radius) { Shape.call(this, id, x, y); this.radius = radius; }; Circle.prototype = Object.create(Shape.prototype); Circle.prototype.constructor = Circle;
class Rectangle extends Shape { constructor (id, x, y, width, height) { super(id, x, y) this.width = width this.height = height } } class Circle extends Shape { constructor (id, x, y, radius) { super(id, x, y) this.radius = radius } }
let fibonacci = { [Symbol.iterator]() { let pre = 0, cur = 1 return { next () { [ pre, cur ] = [ cur, pre + cur ] return { done: false, value: cur } } } } } for (let n of fibonacci) { if (n > 1000) break write(n) }