SlideShare uma empresa Scribd logo
1 de 40
EcmaScript5.1 MASTERING NAMESPACES! Илья Кантор http://javascript.ru
История
varuser=<username="John"> <fieldtype="age"value="25"/> <fieldtype="email"value="john@gmail.com"/> </user> alert(user.field.(@type=="email").@value) 1997 ECMA-262 1st edition 1999 ECMA-2623rd edition  2001 Compact Profile  2004 E4X    —  ECMA-262 4th ed. 2009 ECMA-2625th edition  ???    — ECMA-262Harmony
ECMA-2625th edition  Что нового?
ECMA-2625th edition  Багфиксы
obj={ class:'Menu' } ES3: ошибка ES5: ok
functiontest(str){ varre=/ok/g alert(re.test(str)) } test("ok") test("ok") // true // ES3: false,  ES5: true
alert(parseInt("010")==parseFloat("010")) ES3: false ES5: true
varobj={ a:1, b:2, } vararr[1,2,3,] ES3: error ES5: ok
МетаСвойства
writable = false obj={ class:'Menu' } obj.class='Bird‘ =>obj.class == ‘Menu’
configurable = false obj={ class:'Menu' } deleteobj.class =>obj.class == ‘Menu’
enumerable = false Object.prototype.each=... for(propin{}){ // без свойства ‘each’ }
Объявление Object.defineProperty({},"class", { value:"Menu", writable:false, configurable:false, enumerable:true }) => { “class” : “Menu” } property descriptor
Объявление Object.defineProperties({},{ class:{ value:"Menu", writable:false, configurable:false }, height:{ value:200, configurable:false } }) => { “class” : “Menu”, “height”: 200 }
Закрытие объекта varuser={ name:"Вася", /* ... */ } Object.preventExtensions(user) user.a=5// Нельзя добавлять свойства Object.seal(user) deleteuser.name// Нельзя удалять свойства Object.freeze(user) user.name='Петя'// Нельзя менять свойства
Наследование animal={ canWalk:true } rabbit=Object.create(animal,{ canRun:{ value:true } }) alert(rabbit.canWalk)// true Object.getPrototypeOf(rabbit) == animal // true
Наследование rabbit=Object.create(animal,{ canRun:{ value:true } }) bird=Object.create(Object.getPrototypeOf(rabbit),{ canFly:{ value:true } })
Геттеры и Сеттеры user=Object.defineProperty({},"fullName",{ get:function(){ returnthis.firstName+' '+this.lastName }, set:function(value){ vars=value.trim().split(/+/,2) this.firstName=s[0]; this.lastName=s[1] } })   user.fullName="Вася Пупкин" alert(user.lastName)// Пупкин
Геттеры и Сеттеры varuser={ getfullName(){ returnthis.firstName+' '+this.lastName }, setfullName(value){ vars=value.trim().split(/+/,2) this.firstName=s[0]; this.lastName=s[1] } }   user.fullName="Вася Пупкин" alert(user.lastName)// Пупкин
JSON
JSON event={ title:"Conference", date:“today" } str=JSON.stringify(event) ,[object Object],event =JSON.parse(str) @see https://github.com/douglascrockford/JSON-js
JSON – любые объекты functionRoom(number){ this.toJSON=function(){ returnnumber } } event={ title:"Conference", date:newDate(), room:newRoom(22) } JSON.stringify(event) {"title":"Conference","date":"2011-02-15T09:12:06.836Z","room":22}
JSON – любые объекты functionRoom(number){ this.toJSON=function(){ returnnumber } } event={ title:"Conference", date:newDate(),     Date.prototype.toJSON room:newRoom(22) } JSON.stringify(event) {"title":"Conference","date":"2011-02-15T09:12:06.836Z","room":22}
JSON.stringify(str, whitelist) event={ title:"Conference", date:newDate(), domElement:document.body } JSON.stringify(event) => TypeError: Converting circular structure to JSON JSON.stringify(event,["title","date"]) => {"title":"Conference","date":"2011-02-15T09:44:13.419Z"}
JSON.stringify(str, replacer) event={ title:"Conference", date:newDate(), domElement:document.body } JSON.stringify(event,function(key,value){ returnvalue.nodeName?undefined:value }) => {"title":"Conference","date":"2011-02-15T09:44:13.419Z"}
JSON.parse(str) str='{"title":"Conference",    br />  "date":"2011-02-15T09:44:13.419Z"}' event=JSON.parse(str) пробелы
JSON.parse(str) str='{"title":"Conference",    br />  "date":"2011-02-15T09:44:13.419Z"}' event=JSON.parse(str) event.date.getDay() => TypeError: no method 'getDay'
JSON.parse(str, reviver) str='{"title":"Conference",    br />  "date":"2011-02-15T09:44:13.419Z"}' event=JSON.parse(str,function(key,value){ if(key=='date'){ returnnewDate(value) } returnvalue }) event.date.getDay() => 2
bind
bind(this) functionButton(elem){ this.sayHi=function(){ alert('Hi') } elem.onclick=function(){ this.sayHi() }.bind(this) }
bind(this, args) functionButton(elem){ this.say=function(phrase){ alert(phrase) } elem.onclick=function(event,phrase){ this.say(phrase) }.bind(this,'Hi') } @see http://www.prototypejs.org/api/function/bind
Strict mode
use strict "use strict" ... code ...
use strict functionF(){ "use strict" this.method=function(){ // strict mode inherited } }
use strict alert(010)// SyntaxError (octal literals deprecated) a=5// ReferenceError (undeclared a) obj.notWritable=...// TypeError deleteobj.notConfigurable// TypeError eval("var a = 5") alert(a)// ReferenceError (undeclared a) arguments.callee// TypeError arguments.caller// TypeError (function(){ alert(this)// undefined вместо window })() with(..)// SyntaxError, 'with' statement
Функции,которые давно ждали Object.keys(obj) "String".trim() Array.isArray(arr) [...].indexOf/lastIndexOf [...].forEach [...].map [...].filter [...].reduce/reduceRight // ... @seehttp://kangax.github.com/es5-compat-table/
The future is now ? PrototypeJS ES5-shim
Harmony
It’s all real __noSuchMethod__Proxy.create letblock_scoped="yay!" constREALLY="srsly" #(x) { x * x } ifx>zreturn"без скобок" moduleIter="@std:Iteration"  return[i*iforiinrange(n)] functionprintf(format,...args)ek_scoped= "yay!" consEALLY= "srsly"

Mais conteúdo relacionado

Destaque (18)

P101 B04
P101 B04P101 B04
P101 B04
 
Greg Crowsnest
Greg CrowsnestGreg Crowsnest
Greg Crowsnest
 
Influenza diego
Influenza diegoInfluenza diego
Influenza diego
 
Prevalence And Factors Associated With Smoking Among Students And Staff In Upm
Prevalence And Factors Associated With Smoking Among Students And Staff In UpmPrevalence And Factors Associated With Smoking Among Students And Staff In Upm
Prevalence And Factors Associated With Smoking Among Students And Staff In Upm
 
Wisdom Circles Presentation09
Wisdom Circles Presentation09Wisdom Circles Presentation09
Wisdom Circles Presentation09
 
Edmedia 2014
Edmedia 2014Edmedia 2014
Edmedia 2014
 
Celebrating Mexicans
Celebrating MexicansCelebrating Mexicans
Celebrating Mexicans
 
Ny State Lote Check Point B Exam, Yuqing Hong
Ny State Lote Check Point B Exam, Yuqing HongNy State Lote Check Point B Exam, Yuqing Hong
Ny State Lote Check Point B Exam, Yuqing Hong
 
Lit 1 Worksheet
Lit 1 WorksheetLit 1 Worksheet
Lit 1 Worksheet
 
Pedagogia vocal
Pedagogia vocalPedagogia vocal
Pedagogia vocal
 
a
aa
a
 
Erwartung
ErwartungErwartung
Erwartung
 
Writing J27
Writing  J27Writing  J27
Writing J27
 
Academic Writing
Academic WritingAcademic Writing
Academic Writing
 
Kv
KvKv
Kv
 
Kloet Onderhoud - Bedrijfsprofiel
Kloet Onderhoud - BedrijfsprofielKloet Onderhoud - Bedrijfsprofiel
Kloet Onderhoud - Bedrijfsprofiel
 
Biggest Fan Contest Entry
Biggest  Fan Contest EntryBiggest  Fan Contest Entry
Biggest Fan Contest Entry
 
RSS
RSSRSS
RSS
 

EcmaScript 5.1