Repository: dnbard/es6-guide Branch: master Commit: ecde3d9e329d Files: 16 Total size: 15.4 KB Directory structure: gitextract_ur61tv2e/ ├── .gitignore ├── LICENSE ├── _template.md ├── ecma6/ │ ├── arrayComprehension.md │ ├── arrows.md │ ├── classes.md │ ├── default.md │ ├── destructuring.md │ ├── generators.md │ ├── iterators.md │ ├── let.md │ ├── modules.md │ ├── objectLiterals.md │ └── templateStrings.md ├── examples/ │ └── arrows+promises.js └── readme.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules package.json ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 Alex Bardanov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: _template.md ================================================ > ES6: ```js ``` > Javascript ```js ``` ================================================ FILE: ecma6/arrayComprehension.md ================================================ # Array Comprehension The array comprehension syntax is a JavaScript expression which allows you to quickly assemble a new array based on an existing one. Comprehensions exist in many programming languages and the upcoming *ECMAScript 7* standard defines array comprehensions for JavaScript. > ES7: ```js [for (num of [ 1, 4, 9 ]) Math.sqrt(num)]; ``` > Javascript ```js [ 1, 4, 9 ].map(function(a){ return Math.sqrt(a) }); ``` > ES7: ```js [for (x of [ 1, 2, 3]) for (y of [ 3, 2, 1 ]) x*y] ``` > Javascript ```js var a = [ 1, 2, 3], b = [ 3, 2, 1 ], result = []; for (var i = 0; i < a.length; i ++) for (var j = 0; j < b.length; j ++) result.push(a[i] * b[j]); ``` ================================================ FILE: ecma6/arrows.md ================================================ # Arrows 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. ## Expression bodies > ES6: ```js var odds = evens.map(v => v + 1); var nums = evens.map((v, i) => v + i); ``` > Javascript ```js var odds = evens.map(function (v) { return v + 1; }); var nums = evens.map(function (v, i) { return v + i; }); ``` ## Statement bodies > ES6: ```js nums.forEach(v => { fives.push(v); }); ``` > Javascript ```js nums.forEach(function (v) { fives.push(v); }); ``` ## Lexical `this` > ES6: ```js var bob = { _name: "Bob", _friends: [], printFriends() { this._friends.forEach(f => console.log(this._name + " knows " + f)); } } ``` > Javascript ```js var bob = { _name: "Bob", _friends: [], printFriends: function() { var _this = this; this._friends.forEach(function (f) { return console.log(_this._name + " knows " + f); }); } }; ``` ================================================ FILE: ecma6/classes.md ================================================ # Classes 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. > ES6: ```js class SkinnedMesh{ update(camera) { } static defaultMatrix() { return new THREE.Matrix4(); } } ``` > Javascript ```js function SkinnedMesh() {} SkinnedMesh.prototype.update = function update(camera) { }; SkinnedMesh.defaultMatrix = function defaultMatrix() { return new THREE.Matrix4(); }; ``` ## Constructor > ES6: ```js class SkinnedMesh { constructor(geometry, materials) { this.idMatrix = SkinnedMesh.defaultMatrix(); this.bones = []; this.boneMatrices = []; } update(camera) { } static defaultMatrix() { return new THREE.Matrix4(); } } ``` > Javascript ```js function SkinnedMesh(geometry, materials) { this.idMatrix = SkinnedMesh.defaultMatrix(); this.bones = []; this.boneMatrices = []; } SkinnedMesh.prototype.update = function update(camera) { Function.prototype.update.call(this); }; SkinnedMesh.defaultMatrix = function defaultMatrix() { return new THREE.Matrix4(); }; ``` ## Extends > ES6: ```js class SkinnedMesh extends THREE.Mesh { update(camera) { super.update(); } } ``` > Javascript ```js var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; function SkinnedMesh() { if (_THREEMesh != null) { _THREEMesh.apply(this, arguments); } } _inherits(SkinnedMesh, _THREEMesh); SkinnedMesh.prototype.update = function update(camera) { THREEMesh.prototype.update.call(this); }; ``` ================================================ FILE: ecma6/default.md ================================================ # Default, Rest, Spread 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. ## Default > ES6: ```js function f(x, y=12) { return x + y; } ``` > Javascript ```js function f(x) { var y = arguments[1] === undefined ? 12 : arguments[1]; return x + y; } ``` ## Rest > ES6: ```js function f(x, ...y) { return x * y.length; } ``` > Javascript ```js function f(x) { var y = Array.prototype.slice.call(arguments, 1); return x * y.length; } ``` ## Spread Pass each elem of array as argument > ES6: ```js console.log(...[1,2,3]); ``` > Javascript ```js console.log.apply(console, [1, 2, 3]); ``` ================================================ FILE: ecma6/destructuring.md ================================================ # Destructuring 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. ## List matching > ES6: ```js var [a, , b] = [1,2,3]; ``` > Javascript ```js var ref = [1, 2, 3]; var a = ref[0]; var b = ref[2]; ``` ## Object matching > ES6: ```js var { first: a, second: { something: b }, third: c } = getSomething(); ``` > Javascript ```js var _getSomething = getSomething(); var a = _getSomething.first; var b = _getSomething.second.something; var c = _getSomething.third; ``` ## Object matching shorthand > ES6: ```js var { first, second, third } = getSomething(); ``` > Javascript ```js var _getSomething = getSomething(); var first = _getSomething.first; var second = _getSomething.second; var third = _getSomething.third; ``` ## Parameter destructuring > ES6: ```js function g({name: x}) { console.log(x); } g({name: 5}); ``` > Javascript ```js function g(_ref) { var x = _ref.name; console.log(x); } g({ name: 5 }); ``` ## Fail-soft destructuring > ES6: ```js var [a] = []; ``` a === undefined; ## Fail-soft destructuring with defaults > ES6: ```js var [a = 1] = []; ``` a === 1; ================================================ FILE: ecma6/generators.md ================================================ # Generators 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). > ES6: ```js function* idMaker(){ var index = 0; while(true) yield index++; } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 ``` >Javascript ```js function idMaker(){ var value = 0; return { next: function(){ return { value: ++value }; } } } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 ``` > ES6: ```js function* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3; } function* generator(i){ yield i; yield* anotherGenerator(i); yield i + 10; } var gen = generator(10); console.log(gen.next().value); // 10 console.log(gen.next().value); // 11 console.log(gen.next().value); // 12 console.log(gen.next().value); // 13 console.log(gen.next().value); // 20 ``` ================================================ FILE: ecma6/iterators.md ================================================ # Iterators, For..Of Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in to custom iterator-based iteration with for..of. Don’t require realizing an array, enabling lazy design patterns like LINQ. > ES6 ```js let fibonacci = { [Symbol.iterator]() { let pre = 0, cur = 1; return { next() { [pre, cur] = [cur, pre + cur]; return { done: false, value: cur } } } } } for (var n of fibonacci) { if (n > 1000) break; console.log(n); } ``` ================================================ FILE: ecma6/let.md ================================================ # Let, Const Block-scoped binding constructs. let is the new var. const is single-assignment. Static restrictions prevent use before assignment. > ES6: ```js function f() { { let x; { // okay, block scoped name const x = "sneaky"; // error, const x = "foo"; } // error, already declared in block let x = "inner"; } } ``` > ES6: ```js var pixel = () => { { var x = 1, y = 1; let color = 'red'; } console.log(x, y, color); // 1, 1, undefined. } ``` ================================================ FILE: ecma6/modules.md ================================================ # Modules 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. ## Export module > ES6 ```js export function sum(x, y) { return x + y; } export var pi = 3.141593; ``` > Javascript ```js exports.sum = sum; function sum(x, y) { return x + y; } var pi = exports.pi = 3.141593; ``` ## Import module > ES6: ```js import * as math from "lib/math"; ``` > Javascript ```js var math = require("lib/math"); ``` ## Export default > ES6: ```js export default function(x) { return Math.exp(x); } ``` > Javascript ```js module.exports = function (x) { return Math.exp(x); }; ``` ================================================ FILE: ecma6/objectLiterals.md ================================================ # Enhanced Object Literals 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. ## Shorthands > ES6: ```js var obj = { handler }; ``` > Javascript ```js var obj = { handler: handler }; ``` ## Methods > ES6: ```js var obj = { toString() { return "null"; } }; ``` > Javascript ```js var obj = { toString: function toString() { return "null"; } }; ``` ## Computed (dynamic) property names > ES6: ```js var obj = { [ 'prop_' + (() => 42)() ]: 42 }; ``` > Javascript ```js var obj = {}; obj["prop_" + (function () { return 42; })()] = 42; ``` ================================================ FILE: ecma6/templateStrings.md ================================================ # Template Strings 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. ## Multiline strings > ES6: ```js `In JavaScript this is not legal.` ``` > Javascript ```js "In JavaScript this is\n not legal."; ``` ## Templating > ES6: ```js var name = "Bob", time = "today"; var query = `Hello ${name}, how are you ${time}?` ``` > Javascript ```js var name = "Bob", time = "today"; var query = "Hello " + name + ", how are you " + time + "?"; ``` ================================================ FILE: examples/arrows+promises.js ================================================ return db.getUser(id) .then(user => user.invites) .then(invites => { invites.forEach(invite => invite.accept()); }); ================================================ FILE: readme.md ================================================ # ECMAScript 6 Features ### [Arrows](https://github.com/dnbard/es6-guide/blob/master/ecma6/arrows.md) 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. ### [Classes](https://github.com/dnbard/es6-guide/blob/master/ecma6/classes.md) 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. ### [Enhanced Object Literals](https://github.com/dnbard/es6-guide/blob/master/ecma6/objectLiterals.md) 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. ### [Template Strings](https://github.com/dnbard/es6-guide/blob/master/ecma6/templateStrings.md) 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. ### [Destructuring](https://github.com/dnbard/es6-guide/blob/master/ecma6/destructuring.md) 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. ### [Default, Rest, Spread](https://github.com/dnbard/es6-guide/blob/master/ecma6/default.md) 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. ### [Let, Const](https://github.com/dnbard/es6-guide/blob/master/ecma6/let.md) Block-scoped binding constructs. let is the new var. const is single-assignment. Static restrictions prevent use before assignment. ### [Iterators, For..Of](https://github.com/dnbard/es6-guide/blob/master/ecma6/iterators.md) Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in to custom iterator-based iteration with for..of. Don’t require realizing an array, enabling lazy design patterns like LINQ. ### [Generators](https://github.com/dnbard/es6-guide/blob/master/ecma6/generators.md) 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). ### [Modules](https://github.com/dnbard/es6-guide/blob/master/ecma6/modules.md) 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. # ECMAScript 7 Features ### [Array Comprehension](https://github.com/dnbard/es6-guide/blob/master/ecma6/arrayComprehension.md) The array comprehension syntax is a JavaScript expression which allows you to quickly assemble a new array based on an existing one.