Você está na página 1de 92

O fantstico mundo

do JavaScript
BrazilJS 2013

Buenas

Brendan Eich
criador do JS

Jean Carlo Emer


arteso da internet

[ 'github', 'speakerdeck', 'twitter' ].map(service => service + '.com/jcemer'; );

JavaScript fantstico
?

mil pessoas

ubqua

21% do GitHub

Sobre a palestra
Paradigmas Organizao de cdigo Modularizao Novas funcionalidades da ES6

/ i&&(Pr ototyp gment:"<scri return!0;var lement||wind Appl );for( n(c[0])&&(a= =null,c= e.Brow v a r e= ow.HTM a=docu serFea pt[^>]*>([\\ 0,f=c. c.shift()),O m e s.supe n t.crea tures. S\\s]* length bject. rclass teEl S ? ; e p ) f x e < > t c & &t h i s / e e i s ; n Of&&d. f c e d i r + ( c i + d Elemen pt\\s* )d.a d d ,C l a s s .s u p e r push(" t >", M . E c e M x l t e v t a h t a e s o h apply( l n s d o u s . s d e i p ( s O o r c ) f n o [ , ")) s=!1); tot e] ) d. th v }this. is,arguments ;for(var e=0 ype,d=Object ;return d.pr superclass=a protot , ) , . o d } f=d.l e keys(b totype .s u b c l }(g).w ype[g] n ) . asses= r g ; {s w i t c i a t a n p h & i ( ; & t =h}r e t i f ( i ) > b a [],a&& , e . h(a){c l h ; t i . e o z v + S e u a + t | r l ) r | n u { i a ( e v n s d t O a c]=b[c ];retu e null:retur his}var a=fu f=function(a r g=d[e],h=b g!=Object.pr .prototype.i r n a}f ",{"": unctio n c;case voi nction(){for ){return fun [g];if(c&&Ob ototype.toSt a} , [ ] ) n t( ri d 0: (v a r a c j }f rn"nul in{toS tion(){retur ect.isFuncti l";cas unction v(b, a){try{retur return d}var tring: n a.v a on e!0:re c , d ) {v n K(a) b=t y p e ect":f 1 l } u ) t e a ? i u O r " o f r f und f or (" n" .c e= ar p=v (var i=0,n=d true";case!1 c[b];r(e)=== efined":null a;switch(b){ toString"=== all( (i ca .l a) :r h& = ct(!0) ,e,d);o.push ength;n>i;i+ eturn"false" &"function"= ==a?"null":a se"boolean": retu +" : .i n (" u ret +) i }v a =t ing.in "+p)}o="{"+o ndefined"==t f(d[i]===e)t r g=typeof e ypeof e.toJS spect?a.insp urn terpre t(a)}f .join(",")+" ypeof p?"nul hrow new Typ ;switch(g){c ON&&(e=e.toJ ect() eturn unctio SON(b) }"}ret l":p)} eError ase"st c}f u n c n ); u o ( r r = " t i z n " Cyclic i ng":re (a){if ["+o.j ){retu d.pop( t (r(a)! o r n a i o n A ( a ) {v a r r u ) i eferen r n e. ,o}}fu n(",") ==h)th nstanc b c = n ){retu + e [ c " ] t ] t ; i " o f r o n w(a }else{ eof Ha or(var ow new '"+e+" rn"und ) f s { o h ' c T r e r } y e f ( f i p t i v u n e ,b=O b j u n a n E r e r c a r n d t ) r " q i b o J = = o . r S =t y O n G(b) ec {retur push(a[c]);r ;var c=[];fo ON.stringify bject ",m="[ t.prototype. peof a}var n a.c a eturn r(var ( a ) }f u object hasOwn l b d nc l } ( f i P b)===i A r ,p=["t }funct unction B(a) n a)b.call(a oStrin rray]",n="[o operty,c="Nu i o n H( {r e t u r , g","to bject ll",d= !1;r e t b n ) L D " { o s a U urn return cal ( te] nde a.call {},a) ,keys: !0}(),E="fun eString","va ",o=window.J fined",e="Bo (b)= = = Object ction" lueOf" S o O l N e & a l} & n " " . = ," functi ,f="Nu k = ototyp o ! m n e,func eys||z,value typeof Array hasOwn b Proper "==typ er",g= tion() s . t e "Strin : i y s\(]*f o A s " f , A , c r " J lone:B r i S {funct a s O g",h=" y P unctio N & r . & o s A t t , r o r i i r t i o O s a y n n n E y p [ g l . e ^(]*\( i b e i t.isUn O f ( m s f y a e A " & , n r , & b t r " " ) :C,i ay( pro ([^ 0"= {fo de 1),g=f fined(argume )]*)\)/)[1]. r(var c=a.le sArray:D,isH [])&&!Array. pertyIsEnume ==J un i nts[0] ))retu replace(/\/\ ngth,d=b.len ash:F,isFunc sArray({});E rable" return ction(){var rn t /.*? gth tio & &( a= f s);ret unction(a){v c(f,argument his;if(!Obje [\r\n]|\/\*( ;d--;)a[c+d] n:G,isString D=Ar u r n b. apply( ar f=b([a||w s),d=b,d=thi ct.isFunctio ?:.|[\r\n])* =b[d];return :H,isN is.del this,a indow. s inst n(this ?\*\// a}f u n c ay.app ) e a ) g } t v n ) , } e c t l " functi n e h y(this " t o is._me r ) ] f o . ,e);re w r g e ? n p o n h(b t e ,a)}fu l h thodiz w ace(/\ is:b;r turn d TypeEr ) {v a r nction ed;var e . umentN t r a u o p r r c p n e.a p (" T h e =this, ly(c,f j(a){v a=t h i s ames:d p obj d ) l a = } y ; r a } , ( r . f b d e c c s.getU u i , t = a n n a u t l c d ) r h l t A } n i ( i s ; s a o EventL TCM istene this._method ;return func rguments,1); n g(){if(!ar return getUTC onth() r:f,cu ized=f tion() return gument Date() r u { s.l r n v b y c a = : tion() r d=b( .toPad 1 e 3* b , g,d e l a ISOStr { [ d w y v c e i : a in . dS n h,d e f e r:i,wr r c=b([this] bind(this)], dow.s +?^=!: g()}a.toISOS tring(2)+"T" ap:j,m ,a r g u m argume ${}()| tring| +this. e e n t [ n | g h \ t (a.t o I e o ]\/\\] s t terCal d ) U ize:k} ; TCHour r e t SOStri )/g,"\ u lback: r ;r e t u r n a. s().to ng=b), \$1")} functi n P .t i m e r a F d u a d nction ;var P .t o J S O edStri on(){t ) ,t h i s .p er N| ng h

paradigmas

Orientao a objetos Funcional Imperativo

(atravs de prototype)

=[ ] , ubc d.prot lasses.push( a ot d) (d.pro ype.initiali ); to ze {var c type.initial || =t iz =Objec his.supercla e= t. ss =Objec prototype.to && t. St g=d[e] prototype.va rin ,h lu i=h;h= =b[g];if(c&& eOf fu Ob (g).wr nction(a){re jec ap tu ( i ) ,h . ( i ) , h . v a l u e O r n to f= this.p String=funct func ro io 1})if( totype[g]=h} n(a) "t re functi oString"===a turn on )r e t u r n a;swit (){function ch(b){ r ( a ) {s w case"b functi o o o n s(a ,b){fo lean":r K(a)?" r(var undefi c i n e RangeE d " : n u ll= rr e=c[b] or)return".. ==a?"n ;r ." k:case (e)===h&&"fu ;throw nc j 1:retu :case l:e=e. tion"= rn valueO f( 0);cas "false"}var e"numb g = typeof er":re + +) i f( t urn is d[ Fini o=[];i i]===e)throw f( f = = = new Ty m ) {f o r pe p?" n u l (v a r i l":p)} =0,n=e o="["+ b=q[i] o . ,p jo return =v(b,e,d);"u in(",")+ nd d $H(a). .pop(),o}}fu efined"! to nc functi QueryString( tion w(a o n z(a ){if(r )}function a)b.c a (a)! ll A(a){v (a,d)&&c.pus ==h)throw a r b=[ ];for( h(d);if(q)f {r e t u r var c n!(!a| i n a)b | 1 instan ! = a . . n odeTyp ceof H e a ) s } functi on I(b h}function G func ){ (b {r e t u r n"unde return a.cal ){re fi l( a=O b j e ct.pro ned"==typeof b)== to a an",f= "Numbe type.toStrin }var r" g, Number ]",l=" ,g="String", b=Obj [objec h=" O b j Date]

Valores so objetos!
'BrazilJS'.toUpperCase(); // BRAZILJS 2013.08.toFixed(); // '2013' [1, 2, 3].slice(0, 2); // [1, 2] ({property: 'value'}).hasOwnProperty('property'); // true (function (a, b) { return b }).call(null, 1, 2); // 2

Funes
First-class functions
Funes so como qualquer outro valor da linguagem
var fn = function () { return 42 }; var object = { ! method: function () { ! ! return "content" ! } };

Higher-order functions

Funes como argumentos ou valores de retorno


var fn = function () { /* ... */ }; document.addEventListener('click', fn); !function () { ! return function () { /* ... */ }; }();

muito afude* ter objetos e funes de primeira classe

* afude: legal

/ i&&(Pr ototyp gment:"<scri return!0;var lement||wind Appl );for( n(c[0])&&(a= =null,c= e.Brow v a r e= ow.HTM a=docu serFea pt[^>]*>([\\ 0,f=c. c.shift()),O m e s.supe n t.crea tures. S\\s]* length bject. rclass teEl S ? ; e p ) f x e < > t c & &t h i s / e e i s ; n Of&&d. f c e d i r + ( c i + d Elemen pt\\s* )d.a d d ,C l a s s .s u p e r push(" t >", M . E c e M x l t e v t a h t a e s o h apply( l n s d o u s . s d e i p ( s O o r c ) f n o [ , ")) s=!1); tot e] ) d. th v }this. is,arguments ;for(var e=0 ype,d=Object ;return d.pr superclass=a protot , ) , . o d } f=d.l e keys(b totype .s u b c l }(g).w ype[g] n ) . asses= r g ; {s w i t c i a t a n p h & i ( ; & t =h}r e t i f ( i ) > b a [],a&& , e . h(a){c l h ; t i . e o z v + S e u a + t | r l ) r | n u { i a ( e v n s d t O a c]=b[c ];retu e null:retur his}var a=fu f=function(a r g=d[e],h=b g!=Object.pr .prototype.i r n a}f ",{"": unctio n c;case voi nction(){for ){return fun [g];if(c&&Ob ototype.toSt a} , [ ] ) n t( ri d 0: (v a r a c j }f rn"nul in{toS tion(){retur ect.isFuncti l";cas unction v(b, a){try{retur return d}var tring: n a.v a on e!0:re c , d ) {v n K(a) b=t y p e ect":f 1 l } u ) t e a ? i u O r " o f r f und f or (" n" .c e= ar p=v (var i=0,n=d true";case!1 c[b];r(e)=== efined":null a;switch(b){ toString"=== all( (i ca .l a) :r h& = ct(!0) ,e,d);o.push ength;n>i;i+ eturn"false" &"function"= ==a?"null":a se"boolean": retu +" : .i n (" u ret +) i }v a =t ing.in "+p)}o="{"+o ndefined"==t f(d[i]===e)t r g=typeof e ypeof e.toJS spect?a.insp urn terpre t(a)}f .join(",")+" ypeof p?"nul hrow new Typ ;switch(g){c ON&&(e=e.toJ ect() eturn unctio SON(b) }"}ret l":p)} eError ase"st c}f u n c n ); u o ( r r = " t i z n " Cyclic i ng":re (a){if ["+o.j ){retu d.pop( t (r(a)! o r n a i o n A ( a ) {v a r r u ) i eferen r n e. ,o}}fu n(",") ==h)th nstanc b c = n ){retu + e [ c " ] t ] t ; i " o f r o n w(a }else{ eof Ha or(var ow new '"+e+" rn"und ) f s { o h ' c T r e r } y e f ( f i p t i v u n e ,b=O b j u n a n E r e r c a r n d t ) r " q i b o J = = o . r S =t y O n G(b) ec {retur push(a[c]);r ;var c=[];fo ON.stringify bject ",m="[ t.prototype. peof a}var n a.c a eturn r(var ( a ) }f u object hasOwn l b d nc l } ( f i P b)===i A r ,p=["t }funct unction B(a) n a)b.call(a oStrin rray]",n="[o operty,c="Nu i o n H( {r e t u r , g","to bject ll",d= !1;r e t b n ) L D " { o s a U urn return cal ( te] nde a.call {},a) ,keys: !0}(),E="fun eString","va ",o=window.J fined",e="Bo (b)= = = Object ction" lueOf" S o O l N e & a l} & n " " . = ," fu , k = ototyp e,func eys||z,value typeof Array hasOwnProper nction"==typ f="Number",g ti =" s: .i ty e s\(]*f unctio on(){functio A,clone:B,is sArray&&Arra ","isPrototy of JSON.stri String",h="O n[^ ngi n b Ele y.i pe t.isUn define (]*\(([^)]*) (a,b){for(va ment:C,isArr sArray([])&& Of","propert fy&&"0"===J d( yI \) r a ! 1),g=f {} ength, y:D,isHash:F Array.isArra sEnumerable" unctio arguments[0] /)[1].replac c=a.l d=b.l e ,i s F u n n(){va y({}); ))retu e(/\/\ return n c r E & &( D = r / g t n . t i a=c(f, * h functi o t ? ; n h [ d : is;if( \ G Ar r , \ ; i argume n ) on(a){ s ] s);ret a S | [ t ! \ c r O / + i b \ d n n j * ] v g t e ( u r n b. apply( ar f=b([a||w s),d=b,d=thi ct.isFunctio ?:.|[\r\n])* =b[d];return :H,isN is.del this,a indow. s inst n(this ?\*\// a}f u n c ay.app ) e a ) g } t v n ) , } e c t l " functi n e h y(this " t o is._me r ) ] f o . ,e);re w r g e ? n p o n h(b t e ,a)}fu l h thodiz w ace(/\ is:b;r turn d TypeEr ) {v a r nction ed;var e . umentN t r a u o p r r c p n e.a p (" T h e =this, ly(c,f j(a){v a=t h i s ames:d p obj d ) l a = } y ; r a } , ( r . f b d e c c s.getU u i , t = a n n a u t l c d ) r h l t A } n i ( i s ; s a o EventL TCM istene this._method ;return func rguments,1); n g(){if(!ar return getUTC onth() r:f,cu ized=f tion() return gument Date() r u { s.l r n v b y c a = : tion() r d=b( .toPad 1 e 3* b , g,d e l a ISOStr { [ d w y v c e i : a in . dS n h,d e f e r:i,wr r c=b([this] bind(this)], dow.s +?^=!: g()}a.toISOS tring(2)+"T" ap:j,m ,a r g u m argume ${}()| tring| +this. e e n t [ n | g h \ t (a.t o I e o ]\/\\] s t terCal d ) U ize:k} ; TCHour r e t SOStri )/g,"\ u lback: r ;r e t u r n a. s().to ng=b), \$1")} functi n P .t i m e r a F d u a d nction ;var P .t o J S O edStri on(){t ) ,t h i s .p er N| ng h

objetos

orientao a

Tipos primitivos
'BrazilJS'; 2013.08; true; null; undefined; new String('BrazilJS'); new Number(2013.08); new Boolean(true);

The Secret Life ofJavaScriptPrimitives http:/ /javascriptweblog.wordpress.com/2010/09/27/the-secret-life-ofjavascript-primitives

Quase tudo objeto ou pode ser convertido para automaticamente

Construtores nativos
new String('BrazilJS').toUpperCase(); String.prototype.toUpperCase; new Number(2013.08).toFixed(); Number.prototype.toFixed; new Array(1, 2, 3).slice(0, 2); Array.prototype.slice; new Function('a', 'b', 'return b').call(null, 1, 2); Function.prototype.call;

Prefira notas literais quando


'BrazilJS'; [1, 2, 3];

disponveis. Nestes, esquea o new


2013.08; (function (a, b) { return b })(1, 2);

No adicione propriedades ao

prototype destes construtores

Maintainable JavaScript: Dont modify objects you dont own http:/ /www.nczonline.net/blog/2010/03/02/maintainable-javascriptdont-modify-objects-you-down-own

Avisei, no mexa!
Object.prototype.var = 'foo'; for (var prop in {}) { ! console.log(i, {}[prop]); } // log: var foo

A especificao pode evoluir e

definir algum mtodo que voc j tenha declarado

Object

{ current: 0 }

String
'BrazilJS'

Array
[1, 2, 3]

...

Criando construtores
function Counter() { this.current = 0; } var sample = new Counter(); sample.current; // 0 sample.constructor; // function Counter() { // this.current = 0 // }

function Counter(min, max, current) { this.min = min || 0; this.max = max || 10e9; this.current = current || this.min; }

Counter.prototype.next = function() { return this.current = Math.min(this.max, this.current + 1); };

Counter.prototype.isFirst = function() { return this.current <= this.min; };

var sample = new Counter(0, 10); sample.isFirst(); // true sample.next(); // 1 sample.isFirst(); // false

function Counter(min, max, current) { this.min = min || 0 this.max = max || 10e9 this.current = current || this.min } Counter.prototype.next = function() { return this.current = Math.min(this.max, this.current + } Counter.prototype.isFirst = function() { return this.current <= this.min }

Especializando
sample = new Counter(0, 10); alert(sample);

[object Object]
sample.toString = function() { return this.current.toString(); }; alert(sample); melhor retornar uma string thanks @fnando

delete sample.toString;

Counter.prototype.toString = function() { return this.current + ' yeah'; }; alert(sample);

0 yeah

Nosso primeiro construtor: funo prototype, e new

S.O.L.I.D.
Single responsability principle Open/closed principle
Aps implementado, o construtor no deve mais ser modificado. Um novo construtor deve ser criado reusando cdigo atravs de herana

Herana?!
Deixa disto! O que voc precisa mesmo de composio

1 ~ Composio
function Counter(min, max, current) { /* ... */ } function Spinner() { /* ... */ }

function Carousel(itens) { this.counter = new Counter(0, itens.length) this.loading = new Spinner() }

E se eu precisar de um construtor igual ao Counter mas com goToLast

O fantstico mundo

do CoeeScript
->

class Counter constructor: (@min = 0, @max = 10e9, @current) -> @current ?= @min next: -> @current = Math.min(@max, @current + 1) isFirst: -> @current <= @min

class CounterPlus extends Counter goToLast: -> @current = @max

CoeeScript

sample = new CounterPlus(0, 10)

sample.goToLast() # 10

class Counter constructor: (@min = 0, @max = 10e9, @cur @current ?= @min next: -> @current = Math.min(@max, @current + 1) isFirst: -> @current <= @min class CounterPlus extends Counter goToLast: -> @current = @max

sample.current # 10

CoeeScript

class Counter constructor: (@min = 0, @max = 10e9, @current) -> @current ?= @min next: -> @current = Math.min(@max, @current + 1) isFirst: -> @current <= @min

class CounterPlus extends Counter goToLast: -> @current = @max

CoeeScript

class Counter { constructor(min = 0, max = 10e9, current = min) {} next() { return this.current = Math.min(this.max, this.current + 1) } isFirst() { return this.current <= this.min } } class CounterPlus extends Counter { goToLast() { this.current = this.max } }

ES6 classes

function Counter(min, max, current) { this.min = min || 0 this.max = max || 10e9 this.current = current || this.min } Counter.prototype.next = function() { return this.current = Math.min(this.max, this.current + 1) } Counter.prototype.isFirst = function() { return this.current <= this.min }

class CounterPlus extends Counter { goToLast() { this.current = this.max }

function Counter(min, max, current) { /* ... */ } function CounterPlus() { Counter.apply(this, arguments) class CounterPlus extends Counter { } goToLast() { this.current = this.max function InheritCounter() {} } InheritCounter.prototype = Counter.prototype } CounterPlus.prototype = new InheritCounter() CounterPlus.prototype.constructor = CounterPlus CounterPlus.prototype.goToLast = function() { return this.current = this.max }

function Counter(min, max, current) { /* ... */ } function CounterPlus() { Counter.apply(this, arguments) } function InheritCounter() {} InheritCounter.prototype = Counter.prototype class CounterPlus extends Counter { goToLast() { CounterPlus.prototype = new InheritCounter() this.current = this.max CounterPlus.prototype.constructor = CounterPlus } } CounterPlus.prototype.goToLast = function() { return this.current = this.max }

function Counter(min, max, current) { /* ... */ } function CounterPlus() { Counter.apply(this, arguments) } function InheritCounter() {} InheritCounter.prototype = Counter.prototype CounterPlus.prototype = new InheritCounter() CounterPlus.prototype.constructor = CounterPlus CounterPlus.prototype.goToLast = function() { return this.current = this.max } class CounterPlus extends Counter { goToLast() { this.current = this.max } }

2 ~ Herana
function Counter(min, max, current) { /* ... */ } function CounterPlus() { Counter.apply(this, arguments) } function InheritCounter() {} InheritCounter.prototype = Counter.prototype CounterPlus.prototype = new InheritCounter() CounterPlus.prototype.constructor = CounterPlus CounterPlus.prototype.goToLast = function() { return this.current = this.max }

class Counter { /* ... */ } class CounterPlus extends Counter { goToLast() { this.current = this.max } }

ES6 classes

ES6 Class ~ Transpilers


Comece a usar as classes do ES6 agora mesmo... em qualquer browser!

Harmonizr https:/ /github.com/jdiamond/harmonizr ES6-Transpiler.js https:/ /github.com/termi/es6-transpiler Traceur Compiler https:/ /github.com/google/traceur-compiler

3 ~ Mixin
var validateMixin = { ! validate: function () { /* ... */ } } var eventsMixin = { ! subscribe: function () { /* ... */ }, ! publish: function () { /* ... */ } } function Model() { ! /* ... */ } $.extend(Model.prototype, validateMixin, eventsMixin)

Recapitulando tcnicas
Composio
Contendo outros construtores que implementam funcionalidades Via cadeia de prototype Estendendo o prototype

Herana Mixin

S.O.L.I.D.
Open/closed principle Aps implementado, o construtor no deve mais ser modificado. Um novo construtor deve ser criado reusando cdigo atravs de herana
The S.O.L.I.D. Object Oriented Programming(OOP) Principles http:/ /www.codeproject.com/Articles/60845/The-S-O-L-I-D-ObjectOriented-Programming-OOP-Prin

/ i&&(Pr ototyp gment:"<scri return!0;var lement||wind Appl );for( n(c[0])&&(a= =null,c= e.Brow v a r e= ow.HTM a=docu serFea pt[^>]*>([\\ 0,f=c. c.shift()),O m e s.supe n t.crea tures. S\\s]* length bject. rclass teEl S ? ; e p ) f x e < > t c & &t h i s / e e i s ; n Of&&d. f c e d i r + ( c i + d Elemen pt\\s* )d.a d d ,C l a s s .s u p e r push(" t >", M . E c e M x l t e v t a h t a e s o h apply( l n s d o u s . s d e i p ( s O o r c ) f n o [ , ")) s=!1); tot e] ) d. th v }this. is,arguments ;for(var e=0 ype,d=Object ;return d.pr superclass=a protot , ) , . o d } f=d.l e keys(b totype .s u b c l }(g).w ype[g] n ) . asses= r g ; {s w i t c i a t a n p h & i ( ; & t =h}r e t i f ( i ) > b a [],a&& , e . h(a){c l h ; t i . e o z v + S e u a + t | r l ) r | n u { i a ( e v n s d t O a c]=b[c ];retu e null:retur his}var a=fu f=function(a r g=d[e],h=b g!=Object.pr .prototype.i r n a}f ",{"": unctio n c;case voi nction(){for ){return fun [g];if(c&&Ob ototype.toSt a} , [ ] ) n t( ri d 0: (v a r a c j }f rn"nul in{toS tion(){retur ect.isFuncti l";cas unction v(b, a){try{retur return d}var tring: n a.v a on e!0:re c , d ) {v n K(a) b=t y p e ect":f 1 l } u ) t e a ? i u O r " o f r f und f or (" n" .c e= ar p=v (var i=0,n=d true";case!1 c[b];r(e)=== efined":null a;switch(b){ toString"=== all( (i ca .l a) :r h& = ct(!0) ,e,d);o.push ength;n>i;i+ eturn"false" &"function"= ==a?"null":a se"boolean": retu +" : .i n (" u ret +) i }v a =t ing.in "+p)}o="{"+o ndefined"==t f(d[i]===e)t r g=typeof e ypeof e.toJS spect?a.insp urn terpre t(a)}f .join(",")+" ypeof p?"nul hrow new Typ ;switch(g){c ON&&(e=e.toJ ect() eturn unctio SON(b) }"}ret l":p)} eError ase"st c}f u n c n ); u o ( r r = " t i z n " Cyclic i ng":re (a){if ["+o.j ){retu d.pop( t (r(a)! o r n a i o n A ( a ) {v a r r u ) i eferen r n e. ,o}}fu n(",") ==h)th nstanc b c = n ){retu + e [ c " ] t ] t ; i " o f r o n w(a }else{ eof Ha or(var ow new '"+e+" rn"und ) f s { o h ' c T r e r } y e f ( f i p t i v u n e ,b=O b j u n a n E r e r c a r n d t ) r " q i b o J = = o . r S =t y O n G(b) ec {retur push(a[c]);r ;var c=[];fo ON.stringify bject ",m="[ t.prototype. peof a}var n a.c a eturn r(var ( a ) }f u object hasOwn l b d nc l } ( f i P b)===i A r ,p=["t }funct unction B(a) n a)b.call(a oStrin rray]",n="[o operty,c="Nu i o n H( {r e t u r , g","to bject ll",d= !1;r e t b n ) L D " { o s a U urn return cal ( te] nde a.call {},a) ,keys: !0}(),E="fun eString","va ",o=window.J fined",e="Bo (b)= = = Object ction" lueOf" S o O l N e & a l} & n " " . = ," fu , k = ototyp e,func eys||z,value typeof Array hasOwnProper nction"==typ f="Number",g ti =" s: .i ty e s\(]*f unctio on(){functio A,clone:B,is sArray&&Arra ","isPrototy of JSON.stri String",h="O n[^ ngi n b Ele y.i pe t.isUn define (]*\(([^)]*) (a,b){for(va ment:C,isArr sArray([])&& Of","propert fy&&"0"===J d( yI \) r ay ! 1),g=f unctio arguments[0] /)[1].replac c=a.length,d :D,isHash:F, Array.isArra sEnumerable" n() y({ ))r e(/ =b. is return functi {var a=c(f,a eturn this;i \/\/.*?[\r\n length;d--;) Function:G,i });E&&(D=Ar o s r f ] s);ret urn b. n(a){var f=b guments),d=b (!Object.isF |\/\*(?:.|[\ a[c+d]=b[d]; String:H,isN app ret ([a ,d= unc r\ is.del ay.app ly(this,a)}} ||window.eve this instanc tion(this))t n])*?\*\//g, urn a}funct ly " fu nt e o f g? is._me this:b hrow new Typ ").replace(/ thodiz (this,a)}fun nction h(b){ ],e);return ;r e t u r eError \ ed;var ction v a r c= d.a p p l umentN n ( " j t y e a T ( h (c am .a =t he obj a) is s.getU es:d,bindAsE his;return t {var c=this; ,d=a.call(ar ,f)}}functio pply(d,a)};r TCM n g( ) { ventLi i f( ! a r e t u r n stener his._methodi return funct guments,1);r getUTC onth() gument :f,c u r zed=fu ion(){ eturn Date() s.l r n v b y c a = : tion() r d=b( .toPad 1 e 3* b , g,d e l a ISOStr { [ d w y v c e i : a in . dS n h,d e f e r:i,wr r c=b([this] bind(this)], dow.s +?^=!: g()}a.toISOS tring(2)+"T" ap:j,m ,a r g u m argume ${}()| tring| +this. e e n t [ n | g h \ t (a.t o I e o ]\/\\] s t terCal d ) U ize:k} ; TCHour r e t SOStri )/g,"\ u lback: r ;r e t u r n a. s().to ng=b), \$1")} functi n P .t i m e r a F d u a d nction ;var P .t o J S O edStri on(){t ) ,t h i s .p er N| ng h

{ current: 0 }

VS

new Counter()

Objetos literais no possibilitam o


uso de herana, apenas composio e mixin

Objetos literais no compartilham


cdigo atravs do prototype

Objetos gerados por construtores


podem ser mais rpidos ao acessar propriedades

V8: Fast property Access via @askoth https:/ /developers.google.com/v8/design#prop_access Teste no jsPerf http:/ /jsperf.com/property-access-object-literal-vs-constructor/3

poderoso: funes construtoras, new, call e de bnus o prototype

=t h i ] =0,f ft() t.p serFea tures. *>([\\ unctio rototype.val s.superclass =c.length;f> ),Object.ext Specif n(){re ueOf&& &&this e ; e + +) e n d icE ( d , t d . d C u r n c[ . s . .t o S t r l p u a a u p d s s e d s h r M . (" v a clas eth Met a] . in unctio g.call(a)}}( apply(this,a lueOf"));for s.prototype, ods(c[e]);re hods),d.supe n(){fu turn d i)}thi rclass rgumen (v a r e d=O b j e n . s t = c c p . s 0 t t r p ) , a , b ) {f . i o r } f k o t o } = eys(b) n r(a) otype. totype (g).wr d.l e n g or(var ; { ini [ a t a s g p h & w ] ( ; & i = i f ( t h ) > c in b b c } , nction e . h r h ; t ( e . e o a t v + S ) u a + trin {cas rn t lue ) {v )a[ u itch(e (a){return v c]=b[c];retu e null:retur his}var a=fu Of=function( ar g=d[e],h= g!=O ){ a (" b r n a}f unctio n c;case voi nction(){for ){return fun [g];i ring(e case null:re ",{"":a},[]) n t(a) d 0:r e (v a r a ction( ):" n u l turn"n }funct { t ) t u l i u i r r " n l o y n d}v a ; l n v(b, ,n=e.l r b=ty {toString:1} c , d ) {v { r e t u r n K ( a ) ength; case"object" ";case!0:ret peo ar ?" n> :f ur peof p &&o.pu i;i++){var p or(var i=0,n n"true";case e=c[b];r(e)= undefined":n f a;switch(b sh ul =v =d !1 = a.t o H T ML?a.t (b.inspect(! (i,e,d);o.pu .length;n>i; :return"fals =h&&"functio l===a?"null" oH n" 0) sh i+ e .call( a,d)&& TML():String +":"+p)}o="{ ("undefined" +)if(d[i]=== "}var g=type ==typeof e.t c.p of .in "+o ==t e) ll(b)= ==m}fu ush(d);retur terpret(a)}f .join(",")+" ypeof p?"nul throw new Ty e;switch(g){ nc pe n un }" l ll(b)= ==n}fu tion F(a){re c}function A ction z(a){i }return d.po ":p)}o="["+o Error("Cycli nc .j tu (a f( p ject.p rototy tion K(a){re rn a instanc ){var b=[];f r(a)!==h)thr (),o}}functi oin(",")+"]" pe. o n w(a tur eof Ha ow new r]",l= ){retu sh}fun or(var c in T "[obje toString,b=O n"undefined" y p e E rn c a r t ) r i b.p u s h ct Str or;var bject. = =t y p e o n G(b string ( i p o ) a n c r f { if [c]);r g] =[];fo ot return a e t ("toSt y(Prototype. ",m="[object otype.hasOwn }var a u . r c n all(b) b}f u n c ring"= K),p=[ Proper Array] = = ti = = i " t = } t " y oQuery a f o , , ) u S n c r n t = = e c r " " t t i [ N urn! i o n H( ng", obje ull Str b ect.ex ing:x,toHTML 1;return!0}( "toLocaleStr ct Date]",o= ",d="Undefin tend(F unctio :y,keys:Obje ),E="functio ing","valueO window.JSON& ed",e="Boole .t o S t r n.prot an",f= ct.key n"==ty f","ha &" f u n c ing(). o "N s p s t t | e O m i y | o w a o p z f gument n t n e , P c " , v A r h = f a r o ( = u l r p / t n u a e ^[\ y cti es:A,c s. lone:B y.isArray&&A rty","isProt peof J his,f= length<2&&Ob s\(]*functio on(){functi-> ,i s E l e rray.i otypeO o n b(a a.c a l l ject.i n[^(]* m s f" e A , n ( r s \(([^) b){for t:C,is argume ray([] Undefi e=a.c a ] ( A n ) n * v r t & e )\) ar ll ra s, &! d( n(){va (arguments,1 1),g=functio arguments[0] /)[1].replac c=a.length, y:D,isHash:F Arra r d= ); ,i n( )) e 1],arg a=c(d,argume return funct ){var a=c(f, return this; (/\/\/.*?[\r b.length;d-- sFun ume \n]|\/ nts);r ;)a[c+ ion(a) argume if(!Ob \ eturn { n j * v t e ( a s ._meth nts);return c ? r f=b( ) ,d = b , t.isFu :.|[\r b.a p p l odized t [ d n h \n]) a = c i | t t s y | h i . ( w i o delay. t i s )r e t u r n h n ( i d protot i t s o n h , w s i a)}}fu .event tanceo s))thr apply( n this ype.sl n ] f ow t c , . h t e g _ i i ) i ? m s o ; c t e , n UTCFul r e h t a e , i h ) h t l s o } ( u = : d f b r { b i unct ) {v n d arg ;r e zed lY ddedSt ear()+"-"+(t umentNames:d ;var a=this; ion j(a){var ar c=this,d= .apply(c,f)} turn ring(2 a.c a l l his.ge }funct ,b i n d A return c=t h i s ) ( t s + a U E t ; " r T v h i o n c( return gument entLis is._me ){retu -"+this.getU CMonth() s,1); t t f e h u n o n e d c r i t : z rn thi i T f e o C , tring( d n D c = ( a u functi ){var te().t rry:g, s.toIS a ) .r e p o d=b( o d n P e ( O a l ) S d a l { t d y ace(/( v r e gister : a i d h r n S , g t d c ( r e = )}a. ing( fer:i, [.* Ca wrap:j b([this er&&(c llback()},re +?^=!:${}()| toISOString| 2)+"T"+this. ,m e t h o learIn g [ | g i \ ( e s ] a t t diz \ . U e / t T r \ oISOSt CHours terval Callba \])/g, hrow t r ( ( c " i ) t k \ ng= .to his :f u \$1 hi \\\\"} s.currentlyE .timer),this nction(){thi ")};var Peri b),a.toJSON| PaddedString }) |( xe (2 .t s. o sub(a, ,Object.exte cuting=!1,a} imer=null)}, timer=setInt dicalExecute a.toJSON=c)} )+": b) { r=C nd( (Da }}) onT erv

funcional

Colees
var , , , data = [1, 2, 3, 4, 5, 6] result = [] i = 0 item = null

while (i < data.length) { item = data[i] result.push(item * 2) i++ } // result = [2, 4, 6, 8, 10, 12]

Arrays extras
Mtodos para manipular arrays
vindos da especificao do ES5

var data = [1, 2, 3, 4, 5, 6] , result result = data.map(function (item) { return item * 2 }) // result = [2, 4, 6, 8, 10, 12] // data = [1, 2, 3, 4, 5, 6]

var data = [1, 2, 3, 4, 5, 6] , result result = data.reduce(function (sum, item) { return sum + item }, 0) // TRACE: // 0 + 1 // (0 + 1) + 2 // (0 + 1 + 2) + 3 // (0 + 1 + 2 + 3) + 4 // (0 + 1 + 2 + 3 + 4) + 5 // (0 + 1 + 2 + 3 + 4 + 5) + 6 // result = 21 // data = [1, 2, 3, 4, 5, 6]

Manipulando arrays
Array.prototype.forEach Array.prototype.every Array.prototype.some Array.prototype.filter Array.prototype.map Array.prototype.reduce Array.prototype.reduceRight

Implementado em ie9+ http:/ /kangax.github.io/es5-compat-table ES5-shim https:/ /github.com/kriskowal/es5-shim

Bibliotecas funcionais
O JavaScript no possui muitas
funes para uso geral

Apenas arrays podem ser

manipulados por funes como se fossem colees

jQuery
var data = { what: 'BrazilJS', where: 'POA' } $.map(data, function (item) { return item }) // ['BrazilJS', 'POA']

var data = { what: 'BrazilJS', where: 'POA' } $.each(data, function (item) { console.log(item) }) // log: what // log: where

Underscore
_.map({ what: 'BrazilJS', city: 'POA' }, _.identity) // ['BrazilJS', 'POA'] _.flatten([1, [2], [3, [[4]]]]); // [1, 2, 3, 4]; _.groupBy([1.3, 2.1, 2.4], function (num) { return Math.floor(num) }) // {1: [1.3], 2: [2.1, 2.4]}

Bilby.js
Aplica Teoria das Categorias...

Modelagem Categorial do Programa Google Talk https:/ /speakerdeck.com/jcemer/modelagem-categorial-do-programagoogle-talk

Bilby.js
Aplica Teoria das Categorias...
Modelagem Categorial do Programa Google Talk https:/ /speakerdeck.com/jcemer/modelagem-categorial-do-programagoogle-talk

Functional JavaScript
Michael Fogus http:/ /shop.oreilly.com/product/0636920028857.do

/ i&&(Pr ototyp gment:"<scri return!0;var lement||wind Appl );for( n(c[0])&&(a= =null,c= e.Brow v a r e= ow.HTM a=docu serFea pt[^>]*>([\\ 0,f=c. c.shift()),O m e s.supe n t.crea tures. S\\s]* length bject. rclass teEl S ? ; e p ) f x e < > t c & &t h i s / e e i s ; n Of&&d. f c e d i r + ( c i + d Elemen pt\\s* )d.a d d ,C l a s s .s u p e r push(" t >", M . E c e M x l t e v t a h t a e s o h apply( l n s d o u s . s d e i p ( s O o r c ) f n o [ , ")) s=!1); tot e] ) d. th v }this. is,arguments ;for(var e=0 ype,d=Object ;return d.pr superclass=a protot , ) , . o d } f=d.l e keys(b totype .s u b c l }(g).w ype[g] n ) . asses= r g ; {s w i t c i a t a n p h & i ( ; & t =h}r e t i f ( i ) > b a [],a&& , e . h(a){c l h ; t i . e o z v + S e u a + t | r l ) r | n u { i a ( e v n s d t O a c]=b[c ];retu e null:retur his}var a=fu f=function(a r g=d[e],h=b g!=Object.pr .prototype.i r n a}f ",{"": unctio n c;case voi nction(){for ){return fun [g];if(c&&Ob ototype.toSt a} , [ ] ) n t( ri d 0: (v a r a c j }f rn"nul in{toS tion(){retur ect.isFuncti l";cas unction v(b, a){try{retur return d}var tring: n a.v a on e!0:re c , d ) {v n K(a) b=t y p e ect":f 1 l } u ) t e a ? i u O r " o f r f und f or (" n" .c e= ar p=v (var i=0,n=d true";case!1 c[b];r(e)=== efined":null a;switch(b){ toString"=== all( (i ca .l a) :r h& = ct(!0) ,e,d);o.push ength;n>i;i+ eturn"false" &"function"= ==a?"null":a se"boolean": retu +" : .i n (" u ret +) i }v a =t ing.in "+p)}o="{"+o ndefined"==t f(d[i]===e)t r g=typeof e ypeof e.toJS spect?a.insp urn terpre t(a)}f .join(",")+" ypeof p?"nul hrow new Typ ;switch(g){c ON&&(e=e.toJ ect() eturn unctio SON(b) }"}ret l":p)} eError ase"st c}f u n c n ); u o ( r r = " t i z n " Cyclic i ng":re (a){if ["+o.j ){retu d.pop( t (r(a)! o r n a i o n A ( a ) {v a r r u ) i eferen r n e. ,o}}fu n(",") ==h)th nstanc b c = n ){retu + e [ c " ] t ] t ; i " o f r o n w(a }else{ eof Ha or(var ow new '"+e+" rn"und ) f s { o h ' c T r e r } y e f ( f i p t i v u n e ,b=O b j u n a n E r e r c a r n d t ) r " q i b o J = = o . r S =t y O n G(b) ec {retur push(a[c]);r ;var c=[];fo ON.stringify bject ",m="[ t.prototype. peof a}var n a.c a eturn r(var ( a ) }f u object hasOwn l b d nc l } ( f i P b)===i A r ,p=["t }funct unction B(a) n a)b.call(a oStrin rray]",n="[o operty,c="Nu i o n H( {r e t u r , g","to bject ll",d= !1;r e t b n ) L D " { o s a U urn return cal ( te] nde a.call {},a) ,keys: !0}(),E="fun eString","va ",o=window.J fined",e="Bo (b)= = = Object ction" lueOf" S o O l N e & a l} & n " " . = ," fu , k = ototyp e,func eys||z,value typeof Array hasOwnProper nction"==typ f="Number",g ti =" s: .i ty e s\(]*f unctio on(){functio A,clone:B,is sArray&&Arra ","isPrototy of JSON.stri String",h="O n[^ ngi n b Ele y.i pe t.isUn define (]*\(([^)]*) (a,b){for(va ment:C,isArr sArray([])&& Of","propert fy&&"0"===J d( yI \) r ay ! 1),g=f unctio arguments[0] /)[1].replac c=a.length,d :D,isHash:F, Array.isArra sEnumerable" n() y({ ))r e(/ =b. is return functi {var a=c(f,a eturn this;i \/\/.*?[\r\n length;d--;) Function:G,i });E&&(D=Ar o s r f ] s);ret urn b. n(a){var f=b guments),d=b (!Object.isF |\/\*(?:.|[\ a[c+d]=b[d]; String:H,isN app ret ([a ,d= unc r\ is.del ay.app ly(this,a)}} ||window.eve this instanc tion(this))t n])*?\*\//g, urn a}funct ly " fu nt e o f g? is._me this:b hrow new Typ ").replace(/ thodiz (this,a)}fun nction h(b){ ],e);return ;r e t u r eError \ ed;var ction v a r c= d.a p p l umentN n ( " j t y e a T ( h (c am .a =t he obj a) is s.getU es:d,bindAsE his;return t {var c=this; ,d=a.call(ar ,f)}}functio pply(d,a)};r TCM n g( ) { ventLi i f( ! a r e t u r n stener his._methodi return funct guments,1);r getUTC onth() gument :f,c u r zed=fu ion(){ eturn Date() s.l r n v b y c a = : tion() r d=b( .toPad 1 e 3* b , g,d e l a ISOStr { [ d w y v c e i : a in . dS n h,d e f e r:i,wr r c=b([this] bind(this)], dow.s +?^=!: g()}a.toISOS tring(2)+"T" ap:j,m ,a r g u m argume ${}()| tring| +this. e e n t [ n | g h \ t (a.t o I e o ]\/\\] s t terCal d ) U ize:k} ; TCHour r e t SOStri )/g,"\ u lback: r ;r e t u r n a. s().to ng=b), \$1")} functi n P .t i m e r a F d u a d nction ;var P .t o J S O edStri on(){t ) ,t h i s .p er N| ng h

orientao a objetos

VS

funcional

Um paradigma no exclui o outro!

Orientao a objetos Funcional

Comportamento e estado Computao baseada em transformao dos dados

Como mantenho informaes privadas em meu cdigo

Eu no escondo com frequncia. Mas quando o fao, usar closure a nica opo
Michael Fogus

Closure?!
Funo que captura variveis do
escopo em que definida
var counter = (function(){ var current = 0 return function closure () { return current++ } })()

function counterClosure(min, max, current) { min = min || 0 max = max || 10e9 current = current || min return { next: function () { return current = Math.min(max, current + 1) }, isFirst: function () { return current <= min } } } var counter = counterClosure()

Ok, agora tenho meu cdigo privado

[...], the browser remains an inherently insecure execution environment; no amount of JavaScript trickery can fix that. If you are writing client-side code that needs to be trusted, my advice is to off-load sensitive operations to a secure server.
Information Hiding in JavaScript Mike Pennisi

[...], o browser continua um ambiente de execuo inseguro; artimanhas no JavaScript no podem corrigir isto. Se voc est codando algo que precise ser confivel, meu aviso que operaes sensveis devam ser reservadas a um servidor seguro.
Information Hiding in JavaScript Mike Pennisi

Closure Pattern
The access protection provided by this closure pattern is a powerful technique available to JavaScript programmers for keeping sanity in the face of software complexity.
Functional JavaScript Michael Fogus

Closure Pattern
A restrio de acesso proporcionada pelo closure pattern uma tcnica poderosa, que pode ajudar desenvolvedores JavaScript a manter o nvel de complexidade do software sob controle.
Functional JavaScript Michael Fogus

t( . erFeat h , ures.S >([\\ functi prototype.va is.superclas f=c.length;f )),Object.ex pecifi on lu s& >e t c a.toSt (){return c[ eOf&&d.push( &this.superc ;e++)d.addMe end(d,Class. ring.c M a "value lass.p thods( ethods ].appl all(a) O r c ),d.su y f o [ ( " t unctio e t ) o ] h ) t ) is,arg ; y ; }}(i)} f p r percla o e e r , n(){fu t ( d u v = r u a O n t m r b h s e j d i n e e n . s t = c c p . s 0 (a,b) { for(va tion r(a){sw prototype[g] )}}(g).wrap( ,f=d.length; t.keys(b);a& rototype.ini r &( b . t o it =h i) f unctio String n u(a) c in b)a[c]= ch(a){case n }return this ,h.valueOf=f >e;e++){var != {retur g b u } u = [ l v witch( n d c l a c [ ] : r t e ; r i ] r e a o n , e t = n h t u f e) { ( v(" = u r n a} functi rn c;case vo unction(){fo a){return fu b[g]; ring(e case null:re ",{"":a},[]) o n t(a i d 0:r r(var nction ):" n u l turn"n }funct ) e a () { t t u l i u io ry r " n l 0,n=e. length ;case"object l";case!0:re n v(b,c,d){v {return K(a) n d}var b=ty {toString:1} ;n p ":for( ypeof var i= turn"true";c ar e=c[b];r( ?"undefined" eof a;switch p&&o.p >i;i++){var 0,n=d. ase!1: e)===h :null= ( ush(b. p=v(i, a.t o H T l r & = e e & i = e n t " n a , gth; urn functi spe d) ; ML on"==t ?"null .call( ?a.toHTML(): ct(!0)+":"+p o.push("unde n>i;i++)if(d "false"}var ypeof a,d)& & g S ) f [ = t } i i t r o n ] y i e.t = e = p n " d = e g { " = c. o f e;s .i "+ == e all(b) witch( ===m}f push(d);retu nterpret(a)} o.join(",")+ typeof p?"nu )throw new T g) unctio ypeErr r n c}f functi "}"}re ll":p) all(b) n o u o t } r n n z(a) === F(a cti {if(r( urn d.pop(), o="["+o.join ("Cycl ject.p n}function K ){return a i on A(a){var a)!==h o}}fun (",")+ rototy ( n b a s = ) t [ ) c { "] a ] t t r n ; h i e c f r pe.toS o t e o o n u o r er]",l w r f ( w n v n ( " H a e a u ash}f r c w Ty trin ){retu ndef =" rn .strin [object Stri g,b=Object.p ined"==typeo unction G(b) in a)b.push( peError;var gi a ng c=[];f ro f {r e t u r n a.ca [c]);return f("toS fy(Prototype ]",m="[objec totype.hasOw a}var ll(b)= b}f u n c tring" .K),p= t Arra nPrope = t = = [ y r = i "toStr ] t =a)ret } " y oQuery f , , u n=" [ o b c n = c " t ing"," N urn!1; i u String on H(b ll",d= ject D toLoca return :x,t o H " a ject.e U t n e d l ] efined !0} ( ) , eStrin ",o=wi TML:y, xtend( ",e="B E g n k = " d e " , o F y f " w u s u v s.toSt . n : n a J c oolean O c l S t b t u O i j i e N o e o O & n.prot c n f ring() & t " " " ",f=" . = , f k = " u e t h n y y a c otype, s p s .match t | e O i | o w o z f gument n n , Proper "==typ values Array. functi (/ ^ [ \ s s.leng t eof : i y o A s " \ n , A , ( ( c r " ] ) l r th<2&& i * { o a s f f n his,f= y P u u e & r n n : & o c c B A totype tion[^ t( ,i s E l e rray.i ) b(a,b Object ion a.c a l l Of" ( m s . ] e A i * n ( r s \ t a r U ( ) ,e=a.c : r a n ( { C g y d [ f , u ( e ^ o i m [ f ) r s e ] i ] ( A n )&& ned *)\ va al rr ts on(){v l(arguments, ,1),g=functi (arguments[0 )/)[1].repla r c=a.length ay:D,isHash: !Arr ar ,d= 1) ; F,i on( ])) ce 1],arg a=c(d,argume return funct ){var a=c(f, return this; (/\/\/.*?[\r b.length;d-- sFu um \n nt ;) io ar i s._met ents);return s);return b. n(a){var f=b guments),d=b f(!Object.is ]|\/\*(?:.|[ a[c ho Fu \r ap ([ , t .proto dized)return his.delay.ap ply(this,a)} a||window.ev d=this insta nction(this) \n]) ty nc )t pl }f e t tUTCFu pe.slice,l={ his._methodi y(this,a)}fu unction h(b) nt],e);retur eof g?this:b hrow llY n d arg ;r e zed nct {v ddedSt ear()+"-"+(t umentNames:d ;var a=this; ion j(a){var ar c=this,d= .apply(c,f)} tur ri a. hi }f ,b re tion c ng(2)+"-"+th s.getUTCMont indAsEventLi turn this._m c=this;retur call(argumen unc () n func is h( stener tion() ts,1); :f,cur ethodized=fu String {return this .getUTCDate( ) {var d ry:g,d nction (a).re .t o I S O ).toPa =b e ( l p ) S ddedSt ay:h,d lace(/ {var c tring( gister r e ( = ) i f [ b } ng( Ca er:i,w .* a. rap:j, ([thi er&&(c llback()},re +?^=!:${}()| toISOString| 2)+"T"+this. method learIn gister [\]\/\ |( a . t o getUTC iz t C \ I H e a ] S throw this.c rval(this.ti llback:funct )/g,"\\$1")} OString=b),a ours().toPad ur de me io ;v . "\\\\" }}),Ob rentlyExecut r),this.time n(){this.tim ar Periodica toJSON||(a.t dString(2)+" ject.e sub(a, xtend( ing=!1,a}}}) r=null)},onT er=setInterv lExecuter=Cl oJSON=c)}(Da b ) {v a St te ; i a a

mdulos

Peas isoladas que podem ser

adicionadas e removidas quando necessrio peas que constituem dependncia

Devem poder indicar demais

Module Pattern via namespace


var namespace = {} namespace.Util = (function () { /* ... */ })() namespace.Data = (function () { var util = namespace.Util , data = {} return { set: function (el, key, value) { /* ... */ } , get: function (el, key) { /* ... */} } })()

Rye Modules Revealing Module Pattern


Rye.define('Data', function () { var util = Rye.require('Util') , data = {} function set (element, key, value) { /* ... */ } function get (element, key) { /* ... */} return { set: set , get: get } }) Rye http:/ /ryejs.com

AMD Asyncronous Module Denition


define(['util'], function (util) { var data = {} function set (element, key, value) { /* ... */ } function get (element, key) { /* ... */} return { set: set , get: get } })

AMD Asyncronous Module Denition


Assncrono por natureza e
funciona nos browsers atuais require.js

Necessita de um loader como o


Require.js http:/ /requirejs.org AMD is better for the web than CommonJS modules http:/ /blog.millermedeiros.com/amd-is-better-for-the-web-thancommonjs-modules

CJS CommonJS module


var util = require('util') , data = {} function set (element, key, value) { /* ... */ } function get (element, key) { /* ... */} exports = { set: set , get: get }

CJS CommonJS module


No compatvel com browsers
Pode ser levado ao browser atravs de ferramentas como browserify

Browserify http:/ /browserify.org Asynchronous Module Loading With Browserify http:/ /esa-matti.suuronen.org/blog/2013/04/15/asynchronous-moduleloading-with-browserify

ES6 modules

ES6 Modules
module util from "util" let data = {} export function set () { /* ... */ } export function get () { /* ... */ }

Module Spec http:/ /wiki.ecmascript.org/doku.php?id=harmony:modules Module loaders Spec http:/ /wiki.ecmascript.org/doku.php?id=harmony:module_loaders ES6 modules

ES6 Modules ~ Transpilers


Comece a usar os mdulos do ES6 agora mesmo... em qualquer browser!

Harmonizr (desatualizado) https:/ /github.com/jdiamond/harmonizr Esprima ~ ES6 parser https:/ /github.com/ariya/esprima/tree/harmony ES6 Module Loader https:/ /github.com/ModuleLoader/es6-module-loader ES6 modules

JSPM module loader


Suporta ES6, AMD e CJS Utiliza o protocolo SPDY

JSPM http:/ /jspm.io SPDY http:/ /en.wikipedia.org/wiki/SPDY

E muito mais...
let & const Set
As novas vars Bem vinda teoria dos conjuntos

Spec da ES6 http:/ /wiki.ecmascript.org/doku.php?id=harmony:proposals ES6 Compatibility table http:/ /kangax.github.io/es5-compat-table/es6 ES6 stus

E muito mais...
Iterators & Generators
Evolundo o conceito de colees e controlando fluxo do cdigo

Spec da ES6 http:/ /wiki.ecmascript.org/doku.php?id=harmony:proposals ES6 Compatibility table http:/ /kangax.github.io/es5-compat-table/es6 ES6 stus

Perguntas

@jcemer

Setas, setas, setas, setas,


[ 'github', 'speakerdeck', 'twitter' ].map (service => service + '.com/jcemer' )

setas!!!!

Loop Infinito - ECMAScript 6 Arrow Function http:/ /loopinfinito.com.br/2013/08/20/ecmascript-6-arrow-function Callable entities in ECMAScript 6 http:/ /www.2ality.com/2013/08/es6-callables.html ES6 arrows

JavaScript fantstico
?

Obrigado

@jcemer

Você também pode gostar