TechTalk #86 : ECMAScript 6 by Afief S

Download TechTalk #86 : ECMAScript 6 by Afief S

Post on 24-Jan-2017

589 views

Category:

Software

2 download

TRANSCRIPT

  • By ExamplePresented by Aef S

    ECMASCRIPT 6

  • FEATURESArrowClassesTemplate StringDestructingdefault + rest + spreadlet + constUnicodeModulesModule Loaders

    Map + Set + WeakSymbolsSubclasses built-insPromisesMath + Number + String +

    Array + Object APIsBinary + Octal literals

  • Arrow//Expressionbodiesvarodds=evens.map(v=>v+1);varodds=evens.map(function(v){returnv+1;})varnums=evens.map((v,i)=>v+i);varpairs=evens.map(v=>({even:v,odd:v+1}));//Statementbodiesnums.forEach(v=>{if(v%5===0)fives.push(v);});//Lexicalthisvarbob={_name:"Bob",_friends:[],printFriends(){this._friends.forEach(f=>console.log(this._name+"knows"+f));}}

  • ClassesclassSkinnedMeshextendsTHREE.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();}}

  • Template String//Basicliteralstringcreation`InJavaScript'\n'isalinefeed.`//Multilinestrings`InJavaScriptthisisnotlegal.`//Stringinterpolationvarname="Bob",time="today";`Hello${name},howareyou?`'Hello'+name+',howareyou'+time+'?'//ConstructanHTTPrequestprefixisusedtointerpretthereplacementsandconstructionPOST(`http://foo.org/bar?a=${a}&b=${b}ContentType:application/jsonXCredentials:${credentials}{"foo":${foo},"bar":${bar}}`)(myOnReadyStateChangeHandler);

  • Enhanced ObjectLiterals

    varobj={//__proto____proto__:theProtoObj,//Shorthandforhandler:handlerhandler,//MethodstoString(){//Supercallsreturn"d"+super.toString();},//Computed(dynamic)propertynames['prop_'+(()=>42)()]:42};

  • Destructing//listmatchingvar[a,,b]=[1,2,3];[a,,b];//objectmatchingvar{op:a,lhs:{op:b},rhs:c}=getASTNode()//objectmatchingshorthand//binds`op`,`lhs`and`rhs`inscopevar{op,lhs,rhs}=getASTNode()//{name:'uddin',age:22,kelas:'IT'}op=='uddin'lhs==22rhs=='IT'//Canbeusedinparameterpositionfunctiong({name:x}){console.log(x);}g({name:5})//Failsoftdestructuringvar[a]=[];a===undefined;//Failsoftdestructuringwithdefaultsvar[a=1]=[];a===1;

  • Default + Rest +Spread

    functionf(x,y=12){//yis12ifnotpassed(orpassedasundefined)returnx+y;}

    f(3)==15functionf(x,...y){//yisanArrayreturnx*y.length;}f(3,"hello",true,12)==6//y==['hello',true,12]

    functionf(x,y,z){returnx+y+z;}//Passeachelemofarrayasargumentf(...[1,2,3])==6f(1,2,3)

  • let + constfunctionf(){{letx;{//okay,blockscopednameconstx="sneaky";//error,constx="foo";}x==undefined//error,alreadydeclaredinblockletx="inner";}}

  • Unicode//sameasES5.1"".length==2//newRegExpbehaviour,optinu"".match(/./u)[0].length==2//newform"\u{20BB7}"==""=="\uD842\uDFB7"//newStringops"".codePointAt(0)==0x20BB7//forofiteratescodepointsfor(varcof""){console.log(c);}

  • Modules//lib/math.jsexportfunctionsum(x,y){returnx+y;}exportvarpi=3.141593;

    //app.js'/[root_app]/node_modules/lib/math';import*asmathfrom"lib/math";alert("2="+math.sum(math.pi,math.pi));

    //otherApp.jsimport{sum,pi}from"lib/math";alert("2="+sum(pi,pi));

  • Modules++//lib/mathplusplus.jsexport*from"lib/math";exportvare=2.71828182846;module.exports=function(){}exportdefaultfunction(x){returnMath.log(x);}

    //app.jsimportln,{pi,e}from"lib/mathplusplus";alert("2="+ln(e)*pi*2);

  • Module Loaders//DynamicloadingSystemisdefaultloaderSystem.import('lib/math').then(function(m){alert("2="+m.sum(m.pi,m.pi));});importasdfrom'asd';functiontest(){System.import('./lib/math').then(m=>alert(m));}//CreateexecutionsandboxesnewLoadersvarloader=newLoader({global:fixup(window)//replaceconsole.log});loader.eval("console.log('helloworld!');");//Directlymanipulatemodulecachevar$=System.get('jquery');var$=require('jquery');System.set('jquery',Module({$:$}));//WARNING:notyetfinalized

  • Map + Set + Weak//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;//WeakMapsvarwm=newWeakMap();wm.set(s,{extra:42});wm.size===undefined//WeakSetsvarws=newWeakSet();ws.add({data:42});//Becausetheaddedobjecthasnootherreferences,itwillnotbeheldintheset

  • SymbolsvarMyClass=(function(){//modulescopedsymbolvarkey=Symbol("key");functionMyClass(privateData){constkey2='key2';this[key]=privateData;this[key2]='asd';}MyClass.prototype={doStuff:function(){...this[key]...}};returnMyClass;})();varc=newMyClass("hello")c["key"]===undefined

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

  • New APIsNumber.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('*'))//ReturnsarealArrayArray.of(1,2,3)//SimilartonewArray(...),butwithoutspecialoneargbehavior[0,0,0].fill(7,1)//[0,7,7]_.find([1,2,3],function(x){returnx==4;})[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()//iterator0,1,2["a","b","c"].values()//iterator"a","b","c"Object.assign(Point,{origin:newPoint(0,0)});_.assign(asd,as)varobj={};varobj2={name:'as'};Object.assign(obj,obj2,{age:12})varobj3=Object.freeze({...obj});obj3.kelas='IT';obj3==={name:'as'}obj3.kelas===undefinedobj4=objobj4.kelas=12;obj4==={name:'as',kelas:12};

  • Binary + OctalLiterals

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

  • Terima Kasih