├── tests
├── test-object-literal.html
└── test-class.html
├── REAME_orgn.md
└── README.md
/tests/test-object-literal.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Hello World!
5 |
6 |
7 |
10 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/tests/test-class.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Hello World!
5 |
6 |
7 |
10 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/REAME_orgn.md:
--------------------------------------------------------------------------------
1 | # ECMAScript 6 [git.io/es6features](http://git.io/es6features)
2 |
3 | ## Introduction
4 | ECMAScript 6 is the upcoming version of the ECMAScript standard. This standard is targeting ratification in December 2014. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is [underway now](http://kangax.github.io/es5-compat-table/es6/).
5 |
6 | See the [draft ES6 standard](https://people.mozilla.org/~jorendorff/es6-draft.html) for full specification of the ECMAScript 6 language.
7 |
8 | ES6 includes the following new features:
9 | - [arrows](#arrows)
10 | - [classes](#classes)
11 | - [enhanced object literals](#enhanced-object-literals)
12 | - [template strings](#template-strings)
13 | - [destructuring](#destructuring)
14 | - [default + rest + spread](#default--rest--spread)
15 | - [let + const](#let--const)
16 | - [iterators + for..of](#iterators--forof)
17 | - [generators](#generators)
18 | - [comprehensions](#comprehensions)
19 | - [unicode](#unicode)
20 | - [modules](#modules)
21 | - [module loaders](#module-loaders)
22 | - [map + set + weakmap + weakset](#map--set--weakmap--weakset)
23 | - [proxies](#proxies)
24 | - [symbols](#symbols)
25 | - [subclassable built-ins](#subclassable-built-ins)
26 | - [promises](#promises)
27 | - [math + number + string + object APIs](#math--number--string--object-apis)
28 | - [binary and octal literals](#binary-and-octal-literals)
29 | - [reflect api](#reflect-api)
30 | - [tail calls](#tail-calls)
31 |
32 | ## ECMAScript 6 Features
33 |
34 | ### Arrows
35 | Arrows are a function shorthand using the `=>` syntax. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both expression and statement bodies. Unlike functions, arrows share the same lexical `this` as their surrounding code.
36 |
37 | ```JavaScript
38 | // Expression bodies
39 | var odds = evens.map(v => v + 1);
40 | var nums = evens.map((v, i) => v + i);
41 |
42 | // Statement bodies
43 | nums.forEach(v => {
44 | if (v % 5 === 0)
45 | fives.push(v);
46 | });
47 |
48 | // Lexical this
49 | var bob = {
50 | _name: "Bob",
51 | _friends: [],
52 | printFriends() {
53 | this._friends.forEach(f =>
54 | console.log(this._name + " knows " + f));
55 | }
56 | }
57 | ```
58 |
59 | ### Classes
60 | ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.
61 |
62 | ```JavaScript
63 | class SkinnedMesh extends THREE.Mesh {
64 | constructor(geometry, materials) {
65 | super(geometry, materials);
66 |
67 | this.idMatrix = SkinnedMesh.defaultMatrix();
68 | this.bones = [];
69 | this.boneMatrices = [];
70 | //...
71 | }
72 | update(camera) {
73 | //...
74 | super.update();
75 | }
76 | static defaultMatrix() {
77 | return new THREE.Matrix4();
78 | }
79 | }
80 | ```
81 |
82 | ### Enhanced Object Literals
83 | Object literals are extended to support setting the prototype at construction, shorthand for `foo: foo` assignments, defining methods and making super calls. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.
84 |
85 | ```JavaScript
86 | var obj = {
87 | // __proto__
88 | __proto__: theProtoObj,
89 | // Shorthand for ‘handler: handler’
90 | handler,
91 | // Methods
92 | toString() {
93 | // Super calls
94 | return "d " + super.toString();
95 | },
96 | // Computed (dynamic) property names
97 | [ 'prop_' + (() => 42)() ]: 42
98 | };
99 | ```
100 |
101 | ### Template Strings
102 | Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.
103 |
104 | ```JavaScript
105 | // Basic literal string creation
106 | `In JavaScript '\n' is a line-feed.`
107 |
108 | // Multiline strings
109 | `In JavaScript this is
110 | not legal.`
111 |
112 | // Construct a DOM query
113 | var name = "Bob", time = "today";
114 | `Hello ${name}, how are you ${time}?`
115 |
116 | // Construct an HTTP request prefix is used to interpret the replacements and construction
117 | GET`http://foo.org/bar?a=${a}&b=${b}
118 | Content-Type: application/json
119 | X-Credentials: ${credentials}
120 | { "foo": ${foo},
121 | "bar": ${bar}}`(myOnReadyStateChangeHandler);
122 | ```
123 |
124 | ### Destructuring
125 | Destructuring allows binding using pattern matching, with support for matching arrays and objects. Destructuring is fail-soft, similar to standard object lookup `foo["bar"]`, producing `undefined` values when not found.
126 |
127 | ```JavaScript
128 | // list matching
129 | var [a, , b] = [1,2,3];
130 |
131 | // object matching
132 | var { op: a, lhs: { op: b }, rhs: c }
133 | = getASTNode()
134 |
135 | // object matching shorthand
136 | // binds `op`, `lhs` and `rhs` in scope
137 | var {op, lhs, rhs} = getASTNode()
138 |
139 | // Can be used in parameter position
140 | function g({name: x}) {
141 | console.log(x);
142 | }
143 | g({name: 5})
144 |
145 | // Fail-soft destructuring
146 | var [a] = [];
147 | a === undefined;
148 | ```
149 |
150 | ### Default + Rest + Spread
151 | Callee-evaluated default parameter values. Turn an array into consecutive arguments in a function call. Bind trailing parameters to an array. Rest replaces the need for `arguments` and addresses common cases more directly.
152 |
153 | ```JavaScript
154 | function f(x, y=12) {
155 | // y is 12 if not passed (or passed as undefined)
156 | return x + y;
157 | }
158 | f(3) == 15
159 | ```
160 | ```JavaScript
161 | function f(x, ...y) {
162 | // y is an Array
163 | return x * y.length;
164 | }
165 | f(3, "hello", true) == 6
166 | ```
167 | ```JavaScript
168 | function f(x, y, z) {
169 | return x + y + z;
170 | }
171 | // Pass each elem of array as argument
172 | f(...[1,2,3]) == 6
173 | ```
174 |
175 | ### Let + Const
176 | Block-scoped binding constructs. `let` is the new `var`. `const` is single-assignment. Static restrictions prevent use before assignment.
177 |
178 |
179 | ```JavaScript
180 | function f() {
181 | {
182 | let x;
183 | {
184 | // okay, block scoped name
185 | const x = "sneaky";
186 | // error, const
187 | x = "foo";
188 | }
189 | // error, already declared in block
190 | let x = "inner";
191 | }
192 | }
193 | ```
194 |
195 | ### Iterators + For..Of
196 | Iterator objects enable custom iteration like CLR IEnumerable or Java Iteratable. Generalize `for..in` to custom iterator-based iteration with `for..of`. Don’t require realizing an array, enabling lazy design patterns like LINQ.
197 |
198 | ```JavaScript
199 | let fibonacci = {
200 | [Symbol.iterator]() {
201 | let pre = 0, cur = 1;
202 | return {
203 | next() {
204 | [pre, cur] = [cur, pre + cur];
205 | return { done: false, value: cur }
206 | }
207 | }
208 | }
209 | }
210 |
211 | for (var n of fibonacci) {
212 | // truncate the sequence at 1000
213 | if (n > 1000)
214 | break;
215 | print(n);
216 | }
217 | ```
218 |
219 | Iteration is based on these duck-typed interfaces (using [TypeScript](http://typescriptlang.org) type syntax for exposition only):
220 | ```TypeScript
221 | interface IteratorResult {
222 | done: boolean;
223 | value: any;
224 | }
225 | interface Iterator {
226 | next(): IteratorResult;
227 | }
228 | interface Iterable {
229 | [Symbol.iterator](): Iterator
230 | }
231 | ```
232 |
233 | ### Generators
234 | Generators simplify iterator-authoring using `function*` and `yield`. A function declared as function* returns a Generator instance. Generators are subtypes of iterators which include additional `next` and `throw`. These enable values to flow back into the generator, so `yield` is an expression form which returns a value (or throws).
235 |
236 | Note: Can also be used to enable ‘await’-like async programming, see also ES7 `await` proposal.
237 |
238 | ```JavaScript
239 | var fibonacci = {
240 | [Symbol.iterator]: function*() {
241 | var pre = 0, cur = 1;
242 | for (;;) {
243 | var temp = pre;
244 | pre = cur;
245 | cur += temp;
246 | yield cur;
247 | }
248 | }
249 | }
250 |
251 | for (var n of fibonacci) {
252 | // truncate the sequence at 1000
253 | if (n > 1000)
254 | break;
255 | print(n);
256 | }
257 | ```
258 |
259 | The generator interface is (using [TypeScript](http://typescriptlang.org) type syntax for exposition only):
260 |
261 | ```TypeScript
262 | interface Generator extends Iterator {
263 | next(value?: any): IteratorResult;
264 | throw(exception: any);
265 | }
266 | ```
267 |
268 | ### Comprehensions
269 | Array and generator comprehensions provide simple declarative list processing similar as used in many functional programming patterns.
270 |
271 | ```JavaScript
272 | // Array comprehensions
273 | var results = [
274 | for(c of customers)
275 | if (c.city == "Seattle")
276 | { name: c.name, age: c.age }
277 | ]
278 |
279 | // Generator comprehensions
280 | var results = (
281 | for(c of customers)
282 | if (c.city == "Seattle")
283 | { name: c.name, age: c.age }
284 | )
285 | ```
286 |
287 | ### Unicode
288 | Non-breaking additions to support full Unicode, including new unicode literal form in strings and new RegExp `u` mode to handle code points, as well as new APIs to process strings at the 21bit code points level. These additions support building global apps in JavaScript.
289 |
290 | ```JavaScript
291 | // same as ES5.1
292 | "𠮷".length == 2
293 |
294 | // new RegExp behaviour, opt-in ‘u’
295 | "𠮷".match(/./u)[0].length == 2
296 |
297 | // new form
298 | "\u{20BB7}"=="𠮷"=="\uD842\uDFB7"
299 |
300 | // new String ops
301 | "𠮷".codePointAt(0) == 0x20BB7
302 |
303 | // for-of iterates code points
304 | for(var c of "𠮷") {
305 | console.log(c);
306 | }
307 | ```
308 |
309 | ### Modules
310 | Language-level support for modules for component definition. Codifies patterns from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour defined by a host-defined default loader. Implicitly async model – no code executes until requested modules are available and processed.
311 |
312 | ```JavaScript
313 | // lib/math.js
314 | export function sum(x, y) {
315 | return x + y;
316 | }
317 | export var pi = 3.141593;
318 | ```
319 | ```JavaScript
320 | // app.js
321 | module math from "lib/math";
322 | alert("2π = " + math.sum(math.pi, math.pi));
323 | ```
324 | ```JavaScript
325 | // otherApp.js
326 | import {sum, pi} from "lib/math";
327 | alert("2π = " + sum(pi, pi));
328 | ```
329 |
330 | Some additional features include `export default` and `export *`:
331 |
332 | ```JavaScript
333 | // lib/mathplusplus.js
334 | export * from "lib/math";
335 | export var e = 2.71828182846;
336 | export default function(x) {
337 | return Math.exp(x);
338 | }
339 | ```
340 | ```JavaScript
341 | // app.js
342 | module math from "lib/mathplusplus";
343 | import exp from "lib/mathplusplus";
344 | alert("2π = " + exp(math.pi, math.e));
345 | ```
346 |
347 | ### Module Loaders
348 | Module loaders support:
349 | - Dynamic loading
350 | - State isolation
351 | - Global namespace isolation
352 | - Compilation hooks
353 | - Nested virtualization
354 |
355 | The default module loader can be configured, and new loaders can be constructed to evaluated and load code in isolated or constrained contexts.
356 |
357 | ```JavaScript
358 | // Dynamic loading – ‘System’ is default loader
359 | System.import('lib/math').then(function(m) {
360 | alert("2π = " + m.sum(m.pi, m.pi));
361 | });
362 |
363 | // Create execution sandboxes – new Loaders
364 | var loader = new Loader({
365 | global: fixup(window) // replace ‘console.log’
366 | });
367 | loader.eval("console.log('hello world!');");
368 |
369 | // Directly manipulate module cache
370 | System.get('jquery');
371 | System.set('jquery', Module({$: $})); // WARNING: not yet finalized
372 | ```
373 |
374 | ### Map + Set + WeakMap + WeakSet
375 | Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.
376 |
377 | ```JavaScript
378 | // Sets
379 | var s = new Set();
380 | s.add("hello").add("goodbye").add("hello");
381 | s.size === 2;
382 | s.has("hello") === true;
383 |
384 | // Maps
385 | var m = new Map();
386 | m.set("hello", 42);
387 | m.set(s, 34);
388 | m.get(s) == 34;
389 |
390 | // Weak Maps
391 | var wm = new WeakMap();
392 | wm.set(s, { extra: 42 });
393 | wm.size === undefined
394 |
395 | // Weak Sets
396 | var ws = new WeakSet();
397 | ws.add({ data: 42 });
398 | // Because the added object has no other references, it will not be held in the set
399 | ```
400 |
401 | ### Proxies
402 | Proxies enable creation of objects with the full range of behaviors available to host objects. Can be used for interception, object virtualization, logging/profiling, etc.
403 |
404 | ```JavaScript
405 | // Proxying a normal object
406 | var target = {};
407 | var handler = {
408 | get: function (receiver, name) {
409 | return `Hello, ${name}!`;
410 | }
411 | };
412 |
413 | var p = new Proxy(target, handler);
414 | p.world === 'Hello, world!';
415 | ```
416 |
417 | ```JavaScript
418 | // Proxying a function object
419 | var target = function () { return 'I am the target'; };
420 | var handler = {
421 | apply: function (receiver, ...args) {
422 | return 'I am the proxy';
423 | }
424 | };
425 |
426 | var p = new Proxy(target, handler);
427 | p() === 'I am the proxy';
428 | ```
429 |
430 | There are traps available for all of the runtime-level meta-operations:
431 |
432 | ```JavaScript
433 | var handler =
434 | {
435 | get:...,
436 | set:...,
437 | has:...,
438 | deleteProperty:...,
439 | apply:...,
440 | construct:...,
441 | getOwnPropertyDescriptor:...,
442 | defineProperty:...,
443 | getPrototypeOf:...,
444 | setPrototypeOf:...,
445 | enumerate:...,
446 | ownKeys:...,
447 | preventExtensions:...,
448 | isExtensible:...
449 | }
450 | ```
451 |
452 | ### Symbols
453 | Symbols enable access control for object state. Symbols allow properties to be keyed by either `string` (as in ES5) or `symbol`. Symbols are a new primitive type. Optional `name` parameter used in debugging - but is not part of identity. Symbols are unique (like gensym), but not private since they are exposed via reflection features like `Object.getOwnPropertySymbols`.
454 |
455 |
456 | ```JavaScript
457 | (function() {
458 |
459 | // module scoped symbol
460 | var key = Symbol("key");
461 |
462 | function MyClass(privateData) {
463 | this[key] = privateData;
464 | }
465 |
466 | MyClass.prototype = {
467 | doStuff: function() {
468 | ... this[key] ...
469 | }
470 | };
471 |
472 | })();
473 |
474 | var c = new MyClass("hello")
475 | c["key"] === undefined
476 | ```
477 |
478 | ### Subclassable Built-ins
479 | In ES6, built-ins like `Array`, `Date` and DOM `Element`s can be subclassed.
480 |
481 | Object construction for a function named `Ctor` now uses two-phases (both virtually dispatched):
482 | - Call `Ctor[@@create]` to allocate the object, installing any special behavior
483 | - Invoke constructor on new instance to initialize
484 |
485 | The known `@@create` symbol is available via `Symbol.create`. Built-ins now expose their `@@create` explicitly.
486 |
487 | ```JavaScript
488 | // Pseudo-code of Array
489 | class Array {
490 | constructor(...args) { /* ... */ }
491 | static [Symbol.create]() {
492 | // Install special [[DefineOwnProperty]]
493 | // to magically update 'length'
494 | }
495 | }
496 |
497 | // User code of Array subclass
498 | class MyArray extends Array {
499 | constructor(...args) { super(...args); }
500 | }
501 |
502 | // Two-phase 'new':
503 | // 1) Call @@create to allocate object
504 | // 2) Invoke constructor on new instance
505 | var arr = new MyArray();
506 | arr[1] = 12;
507 | arr.length == 2
508 | ```
509 |
510 | ### Math + Number + String + Object APIs
511 | Many new library additions, including core Math libraries, Array conversion helpers, and Object.assign for copying.
512 |
513 | ```JavaScript
514 | Number.EPSILON
515 | Number.isInteger(Infinity) // false
516 | Number.isNaN("NaN") // false
517 |
518 | Math.acosh(3) // 1.762747174039086
519 | Math.hypot(3, 4) // 5
520 | Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
521 |
522 | "abcde".contains("cd") // true
523 | "abc".repeat(3) // "abcabcabc"
524 |
525 | Array.from(document.querySelectorAll('*')) // Returns a real Array
526 | Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
527 | [0, 0, 0].fill(7, 1) // [0,7,7]
528 | [1,2,3].findIndex(x => x == 2) // 1
529 | ["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
530 | ["a", "b", "c"].keys() // iterator 0, 1, 2
531 | ["a", "b", "c"].values() // iterator "a", "b", "c"
532 |
533 | Object.assign(Point, { origin: new Point(0,0) })
534 | ```
535 |
536 | ### Binary and Octal Literals
537 | Two new numeric literal forms are addded for binary (`b`) and octal (`o`).
538 |
539 | ```JavaScript
540 | 0b111110111 === 503 // true
541 | 0o767 === 503 // true
542 | ```
543 |
544 | ### Promises
545 | Promises are a library for asynchronous programming. Promises are a first class representation of a value that may be made available in the future. Promises are used in many existing JavaScript libraries.
546 |
547 | ```JavaScript
548 | function timeout(duration = 0) {
549 | return new Promise((resolve, reject) => {
550 | setTimeout(resolve, duration);
551 | })
552 | }
553 |
554 | var p = timeout(1000).then(() => {
555 | return timeout(2000);
556 | }).then(() => {
557 | throw new Error("hmm");
558 | }).catch(err => {
559 | return Promise.all([timeout(100), timeout(200)]);
560 | })
561 | ```
562 |
563 | ### Reflect API
564 | Full reflection API exposing the runtime-level meta-operations on objects. This is effectively the inverse of the Proxy API, and allows making calls corresponding to the same meta-operations as the proxy traps. Especially useful for implementing proxies.
565 |
566 | ```JavaScript
567 | // No sample yet
568 | ```
569 |
570 | ### Tail Calls
571 | Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes recursive algorithms safe in the face of unbounded inputs.
572 |
573 | ```JavaScript
574 | function factorial(n, acc = 1) {
575 | 'use strict';
576 | if (n <= 1) return acc;
577 | return factorial(n - 1, n * acc);
578 | }
579 |
580 | // Stack overflow in most implementations today,
581 | // but safe on arbitrary inputs in eS6
582 | factorial(100000)
583 | ```
584 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ECMAScript 6 [git.io/es6features](http://git.io/es6features)
2 |
3 | ## 導入
4 | ECMAScript6(ES6)はECMAScriptスタンダードの次期バージョンであり、2014年10月の承認を目指しています。ES6によって多くのアップデートがJavaScript言語にもたらさます。このような大きな変更は、ES5が2009年に標準になって以来のことです。主要なJavaScriptエンジンにおけるES6の実装状況は[underway now](http://kangax.github.io/es5-compat-table/es6/)を参照してください。
5 |
6 | ECMAScript6の詳細仕様は[draft ES6 standard](https://people.mozilla.org/~jorendorff/es6-draft.html)で公開されています。
7 |
8 | ECMAScript6には次のような新機能が含まれています。
9 | - [Arrows](#arrows)
10 | - [Classes](#classes)
11 | - [Enhanced Object Literals](#enhanced-object-literals)
12 | - [Template Strings](#template-strings)
13 | - [Destructuring](#destructuring)
14 | - [Default + Rest + Spread](#default--rest--spread)
15 | - [Let + Const](#let--const)
16 | - [Iterators + For..of](#iterators--forof)
17 | - [Generators](#generators)
18 | - [Comprehensions](#comprehensions)
19 | - [Unicode](#unicode)
20 | - [Modules](#modules)
21 | - [Module Loaders](#module-loaders)
22 | - [Map + Set + Weakmap + Weakset](#map--set--weakmap--weakset)
23 | - [Proxies](#proxies)
24 | - [Symbols](#symbols)
25 | - [Subclassable Built-ins](#subclassable-built-ins)
26 | - [Math + Number + String + Object APIs](#math--number--string--object-apis)
27 | - [Binary and Octal Literals](#binary-and-octal-literals)
28 | - [Promises](#promises)
29 | - [Reflect API](#reflect-api)
30 | - [Tail Calls](#tail-calls)
31 |
32 | ## ECMAScript6の新機能
33 |
34 | ### Arrows
35 | アロー関数(Arrow Function)は関数の省略記法で`=>`を用いて記述します。これはC#、Java8、CoffeeScriptの機能と似たシンタックスです。アロー関数は1行の式(Expression)としても利用できますし、波括弧`{}`を用いて複数行のステートメント(Statement)としても利用することができます。また、アロー関数内での`this`は通常の関数とは異なります(詳細は以下の例を参照)。
36 |
37 | ```JavaScript
38 | // 1行で用いる場合
39 | var odds = evens.map(v => v + 1);
40 | var nums = evens.map((v, i) => v + i);
41 |
42 | // 複数行で用いる場合
43 | nums.forEach(v => {
44 | if (v % 5 === 0)
45 | fives.push(v);
46 | });
47 |
48 | // thisの参照先
49 | function Person () {
50 | this.age = 0;
51 | setInterval(function () {
52 | //「this = window」になるので意図しない動きになる
53 | console.log(this.age++);
54 | }, 1000);
55 | }
56 |
57 | function Person () {
58 | this.age = 0;
59 | setInterval(() => {
60 | // thisはPersonを指すため、意図した動きになる
61 | console.log(this.age++);
62 | }, 1000);
63 | }
64 | ```
65 |
66 | ### Classes
67 | クラス(Class)はプロトタイプをベースとしていて、オブジェクト指向パターンの上に成り立っています。宣言的な型を独自に定義することでクラスパターンをより利用しやすくなり、また相互運用可能性を促進します。Classはプロトタイプベースの継承をサポートしており、親(super)クラスの呼び出しや、インスタンスメソッド・スタティックメソッドやコンストラクタなどの機能を提供します。
68 |
69 | ```JavaScript
70 | class Animal {
71 | constructor() {
72 | this.id = 'id-' + new Date().getTime();
73 | }
74 | walk () {
75 | console.log('an animal is walking...');
76 | }
77 | static getInstance () {
78 | return new Animal();
79 | }
80 | }
81 |
82 | class Dog extends Animal {
83 | constructor(name) {
84 | super();
85 | this.name = name;
86 | }
87 | walk () {
88 | console.log(this.name + ' is walking...');
89 | }
90 | }
91 | ```
92 |
93 | ### Enhanced Object Literals
94 | オブジェクトリテラルの記述が拡張され、プロトタイプの指定、`foo: foo`の省略記法、メソッドの定義、superの呼び出しを行うことができるようになりました。これによりオブジェクトリテラルとクラス定義をより近しいものとすることができ、同じ機能を持つ異なるものにおいて、オブジェクトベースデザインの利点を享受することができます。
95 |
96 | ```JavaScript
97 | function createObject (name) {
98 | return {
99 | // プロトタイプの指定
100 | __proto__: theProtoObj,
101 | // プロパティの省略定義
102 | name,
103 | // メソッド定義
104 | toString() {
105 | // Super呼び出し
106 | // TODO super.xxx in a object literal doesn't work.
107 | // return "d " + super.toString();
108 | },
109 | // ダイナミックなプロパティ名
110 | [ 'prop_' + (() => 42)() ]: 42
111 | }
112 | }
113 | var obj = createObject('foo');
114 | console.log(obj.name); // foo
115 | ```
116 |
117 | ### Template Strings
118 | テンプレート文字列(Template Strings)は文字列の構築に役立ちます。これはPerlやPythonなどの文字列挿入の形式に似ています。カスタマイズのために任意でタグを文字列の構築に追加することができるため、インジェクション攻撃(injection attack)を防げたり、文字列の組み立てをより簡単に行うことができます。
119 |
120 | ```JavaScript
121 | // 最も基本的な文字列の指定
122 | `In JavaScript '\n' is a line-feed.`
123 |
124 | // 複数行
125 | `In JavaScript this is
126 | not legal.`
127 |
128 | // DOM queryの構築
129 | var name = "Bob", time = "today";
130 | `Hello ${name}, how are you ${time}?`
131 |
132 | // HTTPリクエストを構築する例
133 | GET`http://foo.org/bar?a=${a}&b=${b}
134 | Content-Type: application/json
135 | X-Credentials: ${credentials}
136 | { "foo": ${foo},
137 | "bar": ${bar}}`(myOnReadyStateChangeHandler);
138 | ```
139 | 仕様:[#sec-template-literals](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literals)
140 | 参考:[Template Strings | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings)
141 | Support:FF34+
142 |
143 |
144 |
145 | ### Destructuring
146 | Destructuring allows binding using pattern matching, with support for matching arrays and objects. Destructuring is fail-soft, similar to standard object lookup `foo["bar"]`, producing `undefined` values when not found.
147 |
148 | ### Destructuring
149 | デストラクチャー(Destructuring)はパターンマッチングを用いて、配列やオブジェクトに値を設定することができます。デストラクチャーはフェールソフト(fail-soft)な実装であり、例えば`foo["bar"]`で対象を探し、もし値が見つからない場合には`undefined`が設定されます。
150 |
151 | ```JavaScript
152 | // 配列への代入
153 | var [a, , b] = [1,2,3];
154 |
155 | // オブジェクトへの代入
156 | var { op: a, lhs: { op: b }, rhs: c }
157 | = getASTNode()
158 |
159 | // オブジェクトへの代入(省略記法)
160 | var {op, lhs, rhs} = getASTNode()
161 |
162 | // パラメータにも使うことができます
163 | function g({name: x}) {
164 | console.log(x);
165 | }
166 | g({name: 5})
167 |
168 | // フェールソフトの例
169 | var [a] = [];
170 | a === undefined;
171 | ```
172 |
173 | ### Default + Rest + Spread
174 | Callee-evaluated default parameter values. Turn an array into consecutive arguments in a function call. Bind trailing parameters to an array. Rest replaces the need for `arguments` and addresses common cases more directly.
175 |
176 | ### Default + Rest + Spread
177 | 関数の引数に初期値を設定できます。関数呼び出しで複数のパラメータを指定する場合に、配列で指定することができます。可変引数が利用可能になりました。Rest replaces the need for `arguments` and addresses common cases more directly.
178 |
179 | ```JavaScript
180 | function f(x, y=12) {
181 | // 第2引数が指定されない場合には、y=12となります
182 | return x + y;
183 | }
184 | f(3) == 15
185 | ```
186 | ```JavaScript
187 | function f(x, ...y) {
188 | // yは配列です
189 | return x * y.length;
190 | }
191 | f(3, "hello", true) == 6
192 | ```
193 | ```JavaScript
194 | function f(x, y, z) {
195 | return x + y + z;
196 | }
197 | // 関数の引数を配列形式で指定しています
198 | f(...[1,2,3]) == 6
199 | ```
200 |
201 | ### Let + Const
202 | Block-scoped binding constructs. `let` is the new `var`. `const` is single-assignment. Static restrictions prevent use before assignment.
203 |
204 |
205 | ### Let + Const
206 | 変数宣言の新しい方法です。`let`は`var`の新しい形式で、`const`は一度だけ値を代入することができます。静的な制約を用いることで値代入前に変数を使うことを防ぐことができます。
207 |
208 | ```JavaScript
209 | function f() {
210 | {
211 | let x;
212 | {
213 | // OK: 異なるブロックスコープ内の変数
214 | const x = "sneaky";
215 | // NG: 2度目の代入はダメ
216 | x = "foo";
217 | }
218 | // NG: 既に同一ブロック内で定義済み
219 | let x = "inner";
220 | }
221 | }
222 | ```
223 |
224 | ### Iterators + For..Of
225 | Iterator objects enable custom iteration like CLR IEnumerable or Java Iteratable. Generalize `for..in` to custom iterator-based iteration with `for..of`. Don’t require realizing an array, enabling lazy design patterns like LINQ.
226 |
227 | ### Iterators + For..Of
228 | イテレーターオブジェクト(Iterator Object)はCLRのIEnumberableやJavaのIterableのような、イテレーションを提供します。`for..in`をイテレーションベースにしたものが`for..of`です。配列か否かを気にする必要はなく、LINQなどの遅延デザインパターン(Lazy Design Pattern)を利用することができます。
229 |
230 | ```JavaScript
231 | let fibonacci = {
232 | [Symbol.iterator]() {
233 | let pre = 0, cur = 1;
234 | return {
235 | next() {
236 | [pre, cur] = [cur, pre + cur];
237 | return { done: false, value: cur }
238 | }
239 | }
240 | }
241 | }
242 |
243 | for (var n of fibonacci) {
244 | // 1000で終わり
245 | if (n > 1000)
246 | break;
247 | print(n);
248 | }
249 | ```
250 |
251 | Iteration is based on these duck-typed interfaces (using [TypeScript](http://typescriptlang.org) type syntax for exposition only):
252 |
253 | Iterationは次のようなダックタイピングなインターフェースを元にしています(using [TypeScript](http://typescriptlang.org) type syntax for exposition only)。
254 |
255 | ```TypeScript
256 | interface IteratorResult {
257 | done: boolean;
258 | value: any;
259 | }
260 | interface Iterator {
261 | next(): IteratorResult;
262 | }
263 | interface Iterable {
264 | [Symbol.iterator](): Iterator
265 | }
266 | ```
267 |
268 | ### Generators
269 | Generators simplify iterator-authoring using `function*` and `yield`. A function declared as function* returns a Generator instance. Generators are subtypes of iterators which include additional `next` and `throw`. These enable values to flow back into the generator, so `yield` is an expression form which returns a value (or throws).
270 |
271 | ### Generators
272 | ジェネレーター(Generator)は`function*`と`yield`を用いて、イテレーターの扱いをシンプルにします。`function*`で宣言された関数はジェネレーターのインスタンスを返却します。ジェネレーターはイテレーターのサブタイプであり、`next`と`throw`の機能を追加で保持しています。これらを用いることで値を一連で扱うことができます。`yeild`は返却される値(またはthrowされる値)を表します。
273 |
274 | Note: Can also be used to enable ‘await’-like async programming, see also ES7 `await` proposal.
275 |
276 | 注意:`await`のような非同期プログラミングも利用することができます。詳しくはES7の`await`の提案を参照のこと。
277 |
278 | ```JavaScript
279 | var fibonacci = {
280 | [Symbol.iterator]: function*() {
281 | var pre = 0, cur = 1;
282 | for (;;) {
283 | var temp = pre;
284 | pre = cur;
285 | cur += temp;
286 | yield cur;
287 | }
288 | }
289 | }
290 |
291 | for (var n of fibonacci) {
292 | // truncate the sequence at 1000
293 | if (n > 1000)
294 | break;
295 | print(n);
296 | }
297 | ```
298 |
299 | The generator interface is (using [TypeScript](http://typescriptlang.org) type syntax for exposition only):
300 |
301 | ジェネレーターのインターフェースは次の通りです(using [TypeScript](http://typescriptlang.org) type syntax for exposition only)。
302 |
303 | ```TypeScript
304 | interface Generator extends Iterator {
305 | next(value?: any): IteratorResult;
306 | throw(exception: any);
307 | }
308 | ```
309 |
310 | ### Comprehensions
311 | Array and generator comprehensions provide simple declarative list processing similar as used in many functional programming patterns.
312 |
313 | ### Comprehensions
314 | 配列やジェネレータなどのデータ構造はシンプルな宣言的なリスト機能を提供し、それらは多くの関数型プログラミングのパターンにおいて似たように利用されます。
315 |
316 | ```JavaScript
317 | // 配列
318 | var results = [
319 | for(c of customers)
320 | if (c.city == "Seattle")
321 | { name: c.name, age: c.age }
322 | ]
323 |
324 | // ジェネレーター
325 | var results = (
326 | for(c of customers)
327 | if (c.city == "Seattle")
328 | { name: c.name, age: c.age }
329 | )
330 | ```
331 |
332 | ### Unicode
333 | Non-breaking additions to support full Unicode, including new unicode literal form in strings and new RegExp `u` mode to handle code points, as well as new APIs to process strings at the 21bit code points level. These additions support building global apps in JavaScript.
334 |
335 | ### Unicode
336 | Unicodeがサポートされ、その中には新しいUnicodeの文字が含まれます。正規表現(RegExp)で`u`モードを用いることで扱うことができ、それは21ビットコードポイントレベルの処理を行う新しいAPIと同様です。このサポートによりJavaScriptをグローバルなアプリケーションに利用する手助けとなります。
337 |
338 | ```JavaScript
339 | // ES5.1と同じ
340 | "𠮷".length == 2
341 |
342 | // 新しい世紀表現の利用方法(‘u’の利用)
343 | "𠮷".match(/./u)[0].length == 2
344 |
345 | // 新しい定義方法
346 | "\u{20BB7}"=="𠮷"=="\uD842\uDFB7"
347 |
348 | // コードポイント
349 | "𠮷".codePointAt(0) == 0x20BB7
350 |
351 | // コードポイントによるfor..ofの利用
352 | for(var c of "𠮷") {
353 | console.log(c);
354 | }
355 | ```
356 |
357 | ### Modules
358 | Language-level support for modules for component definition. Codifies patterns from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour defined by a host-defined default loader. Implicitly async model – no code executes until requested modules are available and processed.
359 |
360 | ### Modules
361 | 言語レベルでコンポーネント定義を行うことのできるmoduleがサポートされます。一般的なJavaScriptモジュールローダー(AMDやCommonJSなど)により体系化されたパターンを利用します。ランタイムの振る舞いは、ホストが定義しているデフォルトローダーによって定義されます。これは暗黙的な非同期モデルで、モジュールとして呼び出されたコードはそれが呼び出されるまで、実行されません。
362 |
363 | ```JavaScript
364 | // lib/math.js
365 | export function sum(x, y) {
366 | return x + y;
367 | }
368 | export var pi = 3.141593;
369 | ```
370 | ```JavaScript
371 | // app.js
372 | module math from "lib/math";
373 | alert("2π = " + math.sum(math.pi, math.pi));
374 | ```
375 | ```JavaScript
376 | // otherApp.js
377 | import {sum, pi} from "lib/math";
378 | alert("2π = " + sum(pi, pi));
379 | ```
380 |
381 | Some additional features include `export default` and `export *`:
382 |
383 | `export default`や`export *`などの機能もあります。
384 |
385 | ```JavaScript
386 | // lib/mathplusplus.js
387 | export * from "lib/math";
388 | export var e = 2.71828182846;
389 | export default function(x) {
390 | return Math.exp(x);
391 | }
392 | ```
393 | ```JavaScript
394 | // app.js
395 | module math from "lib/mathplusplus";
396 | import exp from "lib/mathplusplus";
397 | alert("2π = " + exp(math.pi, math.e));
398 | ```
399 |
400 | ### Module Loaders
401 | Module loaders support:
402 | - Dynamic loading
403 | - State isolation
404 | - Global namespace isolation
405 | - Compilation hooks
406 | - Nested virtualization
407 |
408 | ### Module Loaders
409 | モジュールローダーサポート:
410 | - ダイナミックローディング(Dynamic Loading)
411 | - 状態の独立(State Isolation)
412 | - グローバル名前空間の独立(Global Namespace Isolation)
413 | - コンパイルフック(Compilation Hooks)
414 | - ネスト化された仮想化(Nested Virtualization)
415 |
416 | The default module loader can be configured, and new loaders can be constructed to evaluated and load code in isolated or constrained contexts.
417 |
418 | デフォルトモジュールローダーを設定することが可能です。新しいローダーによって独立したコード(またはコンテキストを指定したコード)を構築することができます。
419 |
420 | ```JavaScript
421 | // ダイナミックロードディング – ‘System’はデフォルトローダー
422 | System.import('lib/math').then(function(m) {
423 | alert("2π = " + m.sum(m.pi, m.pi));
424 | });
425 |
426 | // Create execution sandboxes – new Loaders
427 | var loader = new Loader({
428 | global: fixup(window) // replace ‘console.log’
429 | });
430 | loader.eval("console.log('hello world!');");
431 |
432 | // Directly manipulate module cache
433 | System.get('jquery');
434 | System.set('jquery', Module({$: $})); // WARNING: not yet finalized
435 | ```
436 |
437 | ### Map + Set + WeakMap + WeakSet
438 | Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.
439 |
440 | ### Map + Set + WeakMap + WeakSet
441 | 多くのアルゴリズムで有益なデータ構造がサポートされます。WeakMapはメモリリークフリーなKey-Value構造を提供します。
442 |
443 | ```JavaScript
444 | // Set
445 | var s = new Set();
446 | s.add("hello").add("goodbye").add("hello");
447 | s.size === 2;
448 | s.has("hello") === true;
449 |
450 | // Map
451 | var m = new Map();
452 | m.set("hello", 42);
453 | m.set(s, 34);
454 | m.get(s) == 34;
455 |
456 | // Weak Map
457 | var wm = new WeakMap();
458 | wm.set(s, { extra: 42 });
459 | wm.size === undefined
460 |
461 | // Weak Set
462 | var ws = new WeakSet();
463 | ws.add({ data: 42 });
464 | // Because the added object has no other references, it will not be held in the set
465 | ```
466 |
467 | ### Proxies
468 | Proxies enable creation of objects with the full range of behaviors available to host objects. Can be used for interception, object virtualization, logging/profiling, etc.
469 |
470 | ### Proxies
471 | プロキシ(Proxy)を用いることで、ホストオブジェクト(host object)に対して柔軟な振る舞いを設定することができます。処理の割り込みをしたり、オブジェクトの仮想化を行ったり、ロギングやプロファイリングを行うことができます。
472 |
473 | ```JavaScript
474 | // Proxying a normal object
475 | var target = {};
476 | var handler = {
477 | get: function (receiver, name) {
478 | return `Hello, ${name}!`;
479 | }
480 | };
481 |
482 | var p = new Proxy(target, handler);
483 | p.world === 'Hello, world!';
484 | ```
485 |
486 | ```JavaScript
487 | // Proxying a function object
488 | var target = function () { return 'I am the target'; };
489 | var handler = {
490 | apply: function (receiver, ...args) {
491 | return 'I am the proxy';
492 | }
493 | };
494 |
495 | var p = new Proxy(target, handler);
496 | p() === 'I am the proxy';
497 | ```
498 |
499 | There are traps available for all of the runtime-level meta-operations:
500 |
501 | ```JavaScript
502 | var handler =
503 | {
504 | get:...,
505 | set:...,
506 | has:...,
507 | deleteProperty:...,
508 | apply:...,
509 | construct:...,
510 | getOwnPropertyDescriptor:...,
511 | defineProperty:...,
512 | getPrototypeOf:...,
513 | setPrototypeOf:...,
514 | enumerate:...,
515 | ownKeys:...,
516 | preventExtensions:...,
517 | isExtensible:...
518 | }
519 | ```
520 |
521 | ### Symbols
522 | Symbols enable access control for object state. Symbols allow properties to be keyed by either `string` (as in ES5) or `symbol`. Symbols are a new primitive type. Optional `name` parameter used in debugging - but is not part of identity. Symbols are unique (like gensym), but not private since they are exposed via reflection features like `Object.getOwnPropertySymbols`.
523 |
524 | ### Symbols
525 | シンボル(Symbol)はオブジェクトの状態コントロールにアクセスすることを可能にします。シンボルのプロパティには`string(ES5)でも`symbol`でもどちらも取ることができます。シンボルは新しいプリミティブ型です。オプションで`name`プロパティを設定することができデバッグに利用できます(が一意である保証はありません)。シンボルは(gensymのように)固有のものですが、`Object.getOwnPropertySymbols`などの機能を通してシンボルは公開されるので、プライベートではありません。
526 |
527 |
528 | ```JavaScript
529 | (function() {
530 |
531 | // module scoped symbol
532 | var key = Symbol("key");
533 |
534 | function MyClass(privateData) {
535 | this[key] = privateData;
536 | }
537 |
538 | MyClass.prototype = {
539 | doStuff: function() {
540 | ... this[key] ...
541 | }
542 | };
543 |
544 | })();
545 |
546 | var c = new MyClass("hello")
547 | c["key"] === undefined
548 | ```
549 |
550 | ### Subclassable Built-ins
551 | In ES6, built-ins like `Array`, `Date` and DOM `Element`s can be subclassed.
552 |
553 | ### Subclassable Built-ins
554 | ES6では`Array`、`Date`、DOM `Element`といった組み込みクラスのサブクラスを作成することができます。
555 |
556 | Object construction for a function named `Ctor` now uses two-phases (both virtually dispatched):
557 | - Call `Ctor[@@create]` to allocate the object, installing any special behavior
558 | - Invoke constructor on new instance to initialize
559 |
560 | `Ctor`という名前の関数を使ってオブジェクトを生成します。現在は以下2つのステップを行います(以下どちらも仮想的にはディスパッティされています)
561 | - `Ctor[@@create]`を呼び出しオブジェクトの割り当てを行い、独自の振る舞いを定義します。
562 | - コンストラクターを呼び出し、新しいインスタンスを生成します。
563 |
564 | The known `@@create` symbol is available via `Symbol.create`. Built-ins now expose their `@@create` explicitly.
565 |
566 | `@@create`シンボルは、`Symbol.create`を用いて利用することができます。ビルドインクラスは`@@create`を公開しています。
567 |
568 | ```JavaScript
569 | // Arrayクラス(擬似的に再現しています)
570 | class Array {
571 | constructor(...args) { /* ... */ }
572 | static [Symbol.create]() {
573 | // Install special [[DefineOwnProperty]]
574 | // to magically update 'length'
575 | }
576 | }
577 |
578 | // Arrayクラスの独自サブクラス
579 | class MyArray extends Array {
580 | constructor(...args) { super(...args); }
581 | }
582 |
583 | // Two-phase 'new':
584 | // 1) Call @@create to allocate object
585 | // 2) Invoke constructor on new instance
586 | var arr = new MyArray();
587 | arr[1] = 12;
588 | arr.length == 2
589 | ```
590 |
591 | ### Math + Number + String + Object APIs
592 | Many new library additions, including core Math libraries, Array conversion helpers, and Object.assign for copying.
593 |
594 | ### Math + Number + String + Object APIs
595 | Mathライブラリ、Arrayを扱うヘルパー、などの様々な機能が追加され、またコピーのためのObject.assignも追加されました。
596 |
597 | ```JavaScript
598 | Number.EPSILON
599 | Number.isInteger(Infinity) // false
600 | Number.isNaN("NaN") // false
601 |
602 | Math.acosh(3) // 1.762747174039086
603 | Math.hypot(3, 4) // 5
604 | Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
605 |
606 | "abcde".contains("cd") // true
607 | "abc".repeat(3) // "abcabcabc"
608 |
609 | Array.from(document.querySelectorAll('*')) // Returns a real Array
610 | Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
611 | [0, 0, 0].fill(7, 1) // [0,7,7]
612 | [1,2,3].findIndex(x => x == 2) // 1
613 | ["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
614 | ["a", "b", "c"].keys() // iterator 0, 1, 2
615 | ["a", "b", "c"].values() // iterator "a", "b", "c"
616 |
617 | Object.assign(Point, { origin: new Point(0,0) })
618 | ```
619 |
620 | ### Binary and Octal Literals
621 | Two new numeric literal forms are addded for binary (`b`) and octal (`o`).
622 |
623 | ### Binary and Octal Literals
624 | 数値の表現に、`b`を用いたバイナリー記述と`o`を用いた8進数の記述が新たに加わりました。
625 |
626 | ```JavaScript
627 | 0b111110111 === 503 // true
628 | 0o767 === 503 // true
629 | ```
630 |
631 | ### Promises
632 | Promises are a library for asynchronous programming. Promises are a first class representation of a value that may be made available in the future. Promises are used in many existing JavaScript libraries.
633 |
634 | ### Promises
635 | Promiseは非同期プログラミングを行うためのライブラリです。Promiseを用いることで将来利用可能となる値を表現することができます。Promiseは既に多くのJavaScriptライブラリで利用されています。
636 |
637 | ```JavaScript
638 | function timeout(duration = 0) {
639 | return new Promise((resolve, reject) => {
640 | setTimeout(resolve, duration);
641 | })
642 | }
643 |
644 | var p = timeout(1000).then(() => {
645 | return timeout(2000);
646 | }).then(() => {
647 | throw new Error("hmm");
648 | }).catch(err => {
649 | return Promise.all([timeout(100), timeout(200)]);
650 | })
651 | ```
652 |
653 | ### Reflect API
654 | Full reflection API exposing the runtime-level meta-operations on objects. This is effectively the inverse of the Proxy API, and allows making calls corresponding to the same meta-operations as the proxy traps. Especially useful for implementing proxies.
655 |
656 | ### Reflect API
657 | リフレクションAPI(Reflection API)は実行時にオブジェクトのメタ操作を行うことができます。これはProxy APIとは逆のことを提供するものであり、Proxyトラップと同じようなメタ操作に対応する呼び出しを行うことができます。特にProxyを実装する際に有効です。
658 |
659 | ```JavaScript
660 | // No sample yet
661 | ```
662 |
663 | ### Tail Calls
664 | Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes recursive algorithms safe in the face of unbounded inputs.
665 |
666 | ### Tail Calls
667 | テールコール(Tail Call)は上限なきスタックの増加を防ぐことができます。制御しきれないような大きな入力を受け付けた場合にも、再帰呼び出しアルゴリズムを正常に動作させることができます。
668 |
669 |
670 | ```JavaScript
671 | function factorial(n, acc = 1) {
672 | 'use strict';
673 | if (n <= 1) return acc;
674 | return factorial(n - 1, n * acc);
675 | }
676 |
677 | // 現在のほとんどの実装系ではスタックオーバーフロー(Stack Overflow)が発生します
678 | // しかし、ES6ではそれが発生しません
679 | factorial(100000)
680 | ```
681 |
--------------------------------------------------------------------------------