Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Overview of ECMAScript 6 features

License

NotificationsYou must be signed in to change notification settings

lukehoban/es6features

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 

Repository files navigation

Introduction

ECMAScript 6, also known as ECMAScript 2015, is the latest version of the ECMAScript standard. 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 isunderway now.

See theES6 standard for full specification of the ECMAScript 6 language.

ES6 includes the following new features:

ECMAScript 6 Features

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 statement block bodies as well as expression bodies which return the value of the expression. Unlike functions, arrows share the same lexicalthis as their surrounding code.

// Expression bodiesvarodds=evens.map(v=>v+1);varnums=evens.map((v,i)=>v+i);varpairs=evens.map(v=>({even:v,odd:v+1}));// Statement bodiesnums.forEach(v=>{if(v%5===0)fives.push(v);});// Lexical thisvarbob={_name:"Bob",_friends:[],printFriends(){this._friends.forEach(f=>console.log(this._name+" knows "+f));}}

More info:MDN Arrow Functions

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.

classSkinnedMeshextendsTHREE.Mesh{constructor(geometry,materials){super(geometry,materials);this.idMatrix=SkinnedMesh.defaultMatrix();this.bones=[];this.boneMatrices=[];//...}update(camera){//...super.update();}getboneCount(){returnthis.bones.length;}setmatrixType(matrixType){this.idMatrix=SkinnedMesh[matrixType]();}staticdefaultMatrix(){returnnewTHREE.Matrix4();}}

More info:MDN Classes

Enhanced Object Literals

Object literals are extended to support setting the prototype at construction, shorthand forfoo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.

varobj={// __proto____proto__:theProtoObj,// Shorthand for ‘handler: handler’    handler,// MethodstoString(){// Super callsreturn"d "+super.toString();},// Computed (dynamic) property names['prop_'+(()=>42)()]:42};

More info:MDN Grammar and types: Object literals

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.

// Basic literal string creation`In JavaScript '\n' is a line-feed.`// Multiline strings`In JavaScript this is not legal.`// String interpolationvarname="Bob",time="today";`Hello${name}, how are you${time}?`// Construct an HTTP request prefix is used to interpret the replacements and constructionPOST`http://foo.org/bar?a=${a}&b=${b}     Content-Type: application/json     X-Credentials:${credentials}     { "foo":${foo},       "bar":${bar}}`(myOnReadyStateChangeHandler);

More info:MDN Template Strings

Destructuring

Destructuring allows binding using pattern matching, with support for matching arrays and objects. Destructuring is fail-soft, similar to standard object lookupfoo["bar"], producingundefined values when not found.

// list matchingvar[a,,b]=[1,2,3];// object matchingvar{op:a,lhs:{op:b},rhs:c}=getASTNode()// object matching shorthand// binds `op`, `lhs` and `rhs` in scopevar{op, lhs, rhs}=getASTNode()// Can be used in parameter positionfunctiong({name:x}){console.log(x);}g({name:5})// Fail-soft destructuringvar[a]=[];a===undefined;// Fail-soft destructuring with defaultsvar[a=1]=[];a===1;

More info:MDN Destructuring assignment

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 forarguments and addresses common cases more directly.

functionf(x,y=12){// y is 12 if not passed (or passed as undefined)returnx+y;}f(3)==15
functionf(x, ...y){// y is an Arrayreturnx*y.length;}f(3,"hello",true)==6
functionf(x,y,z){returnx+y+z;}// Pass each elem of array as argumentf(...[1,2,3])==6

More MDN info:Default parameters,Rest parameters,Spread Operator

Let + Const

Block-scoped binding constructs.let is the newvar.const is single-assignment. Static restrictions prevent use before assignment.

functionf(){{letx;{// okay, block scoped nameconstx="sneaky";// error, constx="foo";}// error, already declared in blockletx="inner";}}

More MDN info:let statement,const statement

Iterators + For..Of

Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalizefor..in to custom iterator-based iteration withfor..of. Don’t require realizing an array, enabling lazy design patterns like LINQ.

letfibonacci={[Symbol.iterator](){letpre=0,cur=1;return{next(){[pre,cur]=[cur,pre+cur];return{done:false,value:cur}}}}}for(varnoffibonacci){// truncate the sequence at 1000if(n>1000)break;console.log(n);}

Iteration is based on these duck-typed interfaces (usingTypeScript type syntax for exposition only):

interfaceIteratorResult{done:boolean;value:any;}interfaceIterator{next():IteratorResult;}interfaceIterable{[Symbol.iterator]():Iterator}

More info:MDN for...of

Generators

Generators simplify iterator-authoring usingfunction* andyield. A function declared as function* returns a Generator instance. Generators are subtypes of iterators which include additionalnext andthrow. These enable values to flow back into the generator, soyield is an expression form which returns a value (or throws).

Note: Can also be used to enable ‘await’-like async programming, see also ES7await proposal.

varfibonacci={[Symbol.iterator]:function*(){varpre=0,cur=1;for(;;){vartemp=pre;pre=cur;cur+=temp;yieldcur;}}}for(varnoffibonacci){// truncate the sequence at 1000if(n>1000)break;console.log(n);}

The generator interface is (usingTypeScript type syntax for exposition only):

interfaceGeneratorextendsIterator{next(value?:any):IteratorResult;throw(exception:any);}

More info:MDN Iteration protocols

Unicode

Non-breaking additions to support full Unicode, including new Unicode literal form in strings and new RegExpu 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.

// same as ES5.1"𠮷".length==2// new RegExp behaviour, opt-in ‘u’"𠮷".match(/./u)[0].length==2// new form"\u{20BB7}"=="𠮷"=="\uD842\uDFB7"// new String ops"𠮷".codePointAt(0)==0x20BB7// for-of iterates code pointsfor(varcof"𠮷"){console.log(c);}

More info:MDN RegExp.prototype.unicode

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.

// lib/math.jsexportfunctionsum(x,y){returnx+y;}exportvarpi=3.141593;
// app.jsimport*asmathfrom"lib/math";alert("2π = "+math.sum(math.pi,math.pi));
// otherApp.jsimport{sum,pi}from"lib/math";alert("2π = "+sum(pi,pi));

Some additional features includeexport default andexport *:

// lib/mathplusplus.jsexport*from"lib/math";exportvare=2.71828182846;exportdefaultfunction(x){returnMath.log(x);}
// app.jsimportln,{pi,e}from"lib/mathplusplus";alert("2π = "+ln(e)*pi*2);

More MDN info:import statement,export statement

Module Loaders

Module loaders support:

  • Dynamic loading
  • State isolation
  • Global namespace isolation
  • Compilation hooks
  • Nested virtualization

The default module loader can be configured, and new loaders can be constructed to evaluate and load code in isolated or constrained contexts.

// Dynamic loading – ‘System’ is default loaderSystem.import('lib/math').then(function(m){alert("2π = "+m.sum(m.pi,m.pi));});// Create execution sandboxes – new Loadersvarloader=newLoader({global:fixup(window)// replace ‘console.log’});loader.eval("console.log('hello world!');");// Directly manipulate module cacheSystem.get('jquery');System.set('jquery',Module({$:$}));// WARNING: not yet finalized

Map + Set + WeakMap + WeakSet

Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.

// Setsvars=newSet();s.add("hello").add("goodbye").add("hello");s.size===2;s.has("hello")===true;// Mapsvarm=newMap();m.set("hello",42);m.set(s,34);m.get(s)==34;// Weak Mapsvarwm=newWeakMap();wm.set(s,{extra:42});wm.size===undefined// Weak Setsvarws=newWeakSet();ws.add({data:42});// Because the added object has no other references, it will not be held in the set

More MDN info:Map,Set,WeakMap,WeakSet

Proxies

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.

// Proxying a normal objectvartarget={};varhandler={get:function(receiver,name){return`Hello,${name}!`;}};varp=newProxy(target,handler);p.world==='Hello, world!';
// Proxying a function objectvartarget=function(){return'I am the target';};varhandler={apply:function(receiver, ...args){return'I am the proxy';}};varp=newProxy(target,handler);p()==='I am the proxy';

There are traps available for all of the runtime-level meta-operations:

varhandler={get:...,set:...,has:...,deleteProperty:...,apply:...,construct:...,getOwnPropertyDescriptor:...,defineProperty:...,getPrototypeOf:...,setPrototypeOf:...,enumerate:...,ownKeys:...,preventExtensions:...,isExtensible:...}

More info:MDN Proxy

Symbols

Symbols enable access control for object state. Symbols allow properties to be keyed by eitherstring (as in ES5) orsymbol. Symbols are a new primitive type. Optionaldescription 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 likeObject.getOwnPropertySymbols.

varMyClass=(function(){// module scoped symbolvarkey=Symbol("key");functionMyClass(privateData){this[key]=privateData;}MyClass.prototype={doStuff:function(){      ...this[key]...}};returnMyClass;})();varc=newMyClass("hello")c["key"]===undefined

More info:MDN Symbol

Subclassable Built-ins

In ES6, built-ins likeArray,Date and DOMElements can be subclassed.

Object construction for a function namedCtor now uses two-phases (both virtually dispatched):

  • CallCtor[@@create] to allocate the object, installing any special behavior
  • Invoke constructor on new instance to initialize

The known@@create symbol is available viaSymbol.create. Built-ins now expose their@@create explicitly.

// Pseudo-code of ArrayclassArray{constructor(...args){/* ... */}static[Symbol.create](){// Install special [[DefineOwnProperty]]// to magically update 'length'}}// User code of Array subclassclassMyArrayextendsArray{constructor(...args){super(...args);}}// Two-phase 'new':// 1) Call @@create to allocate object// 2) Invoke constructor on new instancevararr=newMyArray();arr[1]=12;arr.length==2

Math + Number + String + Array + Object APIs

Many new library additions, including core Math libraries, Array conversion helpers, String helpers, and Object.assign for copying.

Number.EPSILONNumber.isInteger(Infinity)// falseNumber.isNaN("NaN")// falseMath.acosh(3)// 1.762747174039086Math.hypot(3,4)// 5Math.imul(Math.pow(2,32)-1,Math.pow(2,32)-2)// 2"abcde".includes("cd")// true"abc".repeat(3)// "abcabcabc"Array.from(document.querySelectorAll('*'))// Returns a real ArrayArray.of(1,2,3)// Similar to new Array(...), but without special one-arg behavior[0,0,0].fill(7,1)// [0,7,7][1,2,3].find(x=>x==3)// 3[1,2,3].findIndex(x=>x==2)// 1[1,2,3,4,5].copyWithin(3,0)// [1, 2, 3, 1, 2]["a","b","c"].entries()// iterator [0, "a"], [1,"b"], [2,"c"]["a","b","c"].keys()// iterator 0, 1, 2["a","b","c"].values()// iterator "a", "b", "c"Object.assign(Point,{origin:newPoint(0,0)})

More MDN info:Number,Math,Array.from,Array.of,Array.prototype.copyWithin,Object.assign

Binary and Octal Literals

Two new numeric literal forms are added for binary (b) and octal (o).

0b111110111===503// true0o767===503// true

Promises

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.

functiontimeout(duration=0){returnnewPromise((resolve,reject)=>{setTimeout(resolve,duration);})}varp=timeout(1000).then(()=>{returntimeout(2000);}).then(()=>{thrownewError("hmm");}).catch(err=>{returnPromise.all([timeout(100),timeout(200)]);})

More info:MDN Promise

Reflect API

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.

// No sample yet

More info:MDN Reflect

Tail Calls

Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes recursive algorithms safe in the face of unbounded inputs.

functionfactorial(n,acc=1){'use strict';if(n<=1)returnacc;returnfactorial(n-1,n*acc);}// Stack overflow in most implementations today,// but safe on arbitrary inputs in ES6factorial(100000)

About

Overview of ECMAScript 6 features

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp