mastering namespaces! Илья Кантор ecmascript 5
Post on 19-Jan-2016
242 Views
Preview:
TRANSCRIPT
MASTERING NAMESPACES!
Илья Канторhttp://javascript.ru
EcmaScript 5
История
1997ECMA-262 1st edition
1999ECMA-262 3rd edition
2009ECMA-262 5th edition
???
2001 Compact Profile
2004 E4X
var user = <user name="John"> <field type="age" value="25"/> <field type="email" value="john@gmail.com"/> </user> alert( user.field.(@type == "email").@value )
— ECMA-262 4th ed.
— ECMA-262 Harmony
Что нового?
ECMA-262 5th edition
Багфиксы
ECMA-262 5th edition
obj = { class: 'Menu' }
ES3: ошибкаES5: ok
function test(str) { var re = /ok/g alert( re.test(str) )}
test("ok") test("ok")
// true// ES3: false, ES5: true
alert( parseInt("010") == parseFloat("010") )
ES3: falseES5: true
var obj = { a: 1, b: 2,}
var arr [ 1, 2, 3, ]
ES3: errorES5: ok
МетаСвойства
writable = falseobj = { class: 'Menu'}
obj.class = 'Bird‘
=> obj.class == ‘Menu’
configurable = falseobj = { class: 'Menu'}
=> obj.class == ‘Menu’
delete obj.class
enumerable = false
Object.prototype.each = ...
for(prop in {}) { // без свойства ‘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 }
Закрытие объекта
var user = { name: "Вася", /* ... */}
Object.preventExtensions(user)
Object.seal(user)
Object.freeze(user)
user.a = 5 // Нельзя добавлять свойства
delete user.name // Нельзя удалять свойства
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() { return this.firstName+' '+this.lastName
}, set: function(value) { var s = value.trim().split(/\s+/, 2) this.firstName = s[0]; this.lastName = s[1]
} }) user.fullName = "Вася Пупкин"alert(user.lastName) // Пупкин
Геттеры и Сеттерыvar user = { get fullName () { return this.firstName+' '+this.lastName }, set fullName (value) { var s = value.trim().split(/\s+/, 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)
Þ {"title":"Conference","date":"today"}
event = JSON.parse(str)
@see https://github.com/douglascrockford/JSON-js
JSON – любые объектыfunction Room(number) { this.toJSON = function() { return number }}
event = { title: "Conference", date: new Date(), room: new Room(22)}
JSON.stringify(event)
{"title":"Conference","date":"2011-02-15T09:12:06.836Z","room":22}
JSON – любые объектыfunction Room(number) { this.toJSON = function() { return number }}
event = { title: "Conference", date: new Date(), Date.prototype.toJSON room: new Room(22)}
JSON.stringify(event)
{"title":"Conference","date":"2011-02-15T09:12:06.836Z","room":22}
JSON.stringify(str, whitelist)
event = { title: "Conference", date: new Date(), domElement: document.body }
JSON.stringify(event, ["title", "date"])=> {"title":"Conference","date":"2011-02-15T09:44:13.419Z"}
JSON.stringify(event)=> TypeError: Converting circular structure to JSON
JSON.stringify(str, replacer)
event = { title: "Conference", date: new Date(), domElement: document.body }
JSON.stringify(event, function(key, value) { return value.nodeName ? undefined : value})
=> {"title":"Conference","date":"2011-02-15T09:44:13.419Z"}
JSON.parse(str)
str = '{"title":"Conference", \ "date":"2011-02-15T09:44:13.419Z"}'
event = JSON.parse(str)
пробелы
JSON.parse(str)
str = '{"title":"Conference", \ "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", \ "date":"2011-02-15T09:44:13.419Z"}'
event = JSON.parse(str, function(key, value) { if (key == 'date') { return new Date(value) } return value})
event.date.getDay()
=> 2
bind
bind(this)function Button(elem) { this.sayHi = function() { alert('Hi') } elem.onclick = function() { this.sayHi() }.bind(this) }
bind(this, args)function Button(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"
... code ...
use strict
function F() { "use strict" this.method = function() { // strict mode inherited }}
use strict
alert(010) // SyntaxError (octal literals deprecated)
use strict
a = 5 // ReferenceError (undeclared a)
obj.notWritable = ... // TypeErrordelete obj.notConfigurable // TypeError
eval("var a = 5") alert(a) // ReferenceError (undeclared a)
arguments.callee // TypeErrorarguments.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// ...
@see http://kangax.github.com/es5-compat-table/
Harmony
__noSuchMethod__ Proxy.create
let block_scoped = "yay!"
const REALLY = "srsly"
#(x) { x * x }
if x > z return "без скобок"
module Iter = "@std:Iteration"
return [i * i for i in range(n)]
function printf(format, ...args)ek_scoped = "yay!" consEALLY = "srsly"
It’s all real
top related