SlideShare une entreprise Scribd logo
1  sur  40
EcmaScript 5.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 ? ECMAScript 5 compatibility table  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"

Contenu connexe

En vedette (17)

Such A Beautiful Story
Such A Beautiful StorySuch A Beautiful Story
Such A Beautiful Story
 
Latitude and longitude
Latitude and longitudeLatitude and longitude
Latitude and longitude
 
Reportes de-evaluacion-2014-2015
Reportes de-evaluacion-2014-2015Reportes de-evaluacion-2014-2015
Reportes de-evaluacion-2014-2015
 
Tríptico jornada smarzo2012
Tríptico jornada smarzo2012Tríptico jornada smarzo2012
Tríptico jornada smarzo2012
 
Islandora overview - Drupal Meetup Wellington
Islandora overview - Drupal Meetup WellingtonIslandora overview - Drupal Meetup Wellington
Islandora overview - Drupal Meetup Wellington
 
Home Study Questionnaire Joint
Home Study Questionnaire JointHome Study Questionnaire Joint
Home Study Questionnaire Joint
 
Συλλογικοί Κατάλογοι & Διαδίκτυο
Συλλογικοί Κατάλογοι & ΔιαδίκτυοΣυλλογικοί Κατάλογοι & Διαδίκτυο
Συλλογικοί Κατάλογοι & Διαδίκτυο
 
Jorge Delgado Work
Jorge Delgado  WorkJorge Delgado  Work
Jorge Delgado Work
 
Brazil All
Brazil AllBrazil All
Brazil All
 
Tam su cua ba me
Tam su cua ba meTam su cua ba me
Tam su cua ba me
 
El patito feo
El patito feoEl patito feo
El patito feo
 
Dizzee Rascal Research Tongue N Cheek
Dizzee Rascal Research   Tongue N CheekDizzee Rascal Research   Tongue N Cheek
Dizzee Rascal Research Tongue N Cheek
 
News Fotoss
News FotossNews Fotoss
News Fotoss
 
Increasing Customer Engagement with Social Media
Increasing Customer Engagement with Social MediaIncreasing Customer Engagement with Social Media
Increasing Customer Engagement with Social Media
 
В облаке AWS
В облаке AWSВ облаке AWS
В облаке AWS
 
Big Book by Yana Yu
Big Book by Yana YuBig Book by Yana Yu
Big Book by Yana Yu
 
Raising Fund For Teaching Chinese
Raising Fund For Teaching ChineseRaising Fund For Teaching Chinese
Raising Fund For Teaching Chinese
 

Es51