SlideShare uma empresa Scribd logo
1 de 33
Baixar para ler offline
@HelsinkiJS meet-up
       December 12, 2011




   ECMAScript, 6

     Dmitry Soshnikov
http://dmitrysoshnikov.com
Function parameter
  default values
Function parameter
            default values
function handleRequest(data, method) {
  method = method || “GET”;
  ...
}
Function parameter
            default values
function handleRequest(data, method) {
  method = method || “GET”;
  ...
}
function handleRequest(data, method = “GET”) {
  ...
}
Modules system
Modules in ES3, ES5
var DBLayer = (function (global) {
   /* save original */
   var originalDBLayer = global.DBLayer;
   function noConflict() {
      global.DBLayer = originalDBLayer;    1.   Create local scope
   }                                       2.   Restoring function
   /* implementation */                    3.   Implementation
                                           4.   Public API
   function query() { ... }
   /* exports, public API */
   return {
      noConflict: noConflict,
      query: query
   };
})(this);
Modules in ES3, ES5
var DBLayer = (function (global) {
   /* save original */
   var originalDBLayer = global.DBLayer;
   function noConflict() {
      global.DBLayer = originalDBLayer;    1.    Create local scope
   }                                       2.    Restoring function
   /* implementation */                    3.    Implementation
                                           4.    Public API
   function query() { ... }
   /* exports, public API */
                                                Too much of “noise”.
   return {                                     A “sugar” is needed.
      noConflict: noConflict,
      query: query
   };
})(this);
Modules in ES6
module DBLayer {
  export function query(s) { ... }
  export function connection(...args) { ... }
}

import * from DBLayer; // import all

// import only needed exports
import {query, connection: attachTo} from DBLayer

query(“SELECT * FROM books”).format(“escape | split”);

attachTo(“/books/store”, {
   onSuccess: function (response) { ... }
})
Quasi-Literals
(String templates)
Quasis : string templates
let content = “<a href=‘” + url + “’ title=‘”
  + title + “’>” + text+ “</a>”;

$(“#bar”).html(content);
Quasis : string templates
let content = “<a href=‘” + url + “’ title=‘”
  + title + “’>” + text+ “</a>”;

$(“#bar”).html(content);

let content = safeHtml `<a href=“${url} “ title=“${title}”>${text}</a>`;

$(“#bar”).html(content);

See: http://wiki.ecmascript.org/doku.php?id=harmony:quasis
Array comprehensions
Array comprehensions
// map + filter way
let scores = [1, 7, 4, 9]
  .filter(function (x) { return x > 5 })
  .map(function (x) { return x * x }); // [49, 81]
Array comprehensions
// map + filter way
let scores = [1, 7, 4, 9]
  .filter(function (x) { return x > 5 })
  .map(function (x) { return x * x }); // [49, 81]


// array comprehensions
let scores = [x * x for (x in values([1, 7, 4, 9])) if (x > 5)];
Map and WeakMap
Map and WeakMap
let user = {name: “Ann”, x: 10, y: 20};
// Keys in a map are objects
let scoresMap = new Map;
map.set(user, 100);
console.log(scoresMap.get(user)); // 100
Map and WeakMap
let user = {name: “Ann”, x: 10, y: 20};
// Keys in a map are objects
let scoresMap = new Map;
map.set(user, 100);
console.log(scoresMap.get(user)); // 100

let markers = new WeakMap;
marker = new Marker(10, 20);
markers.set(marker, “Ann”);
console.log(weakMap.get(marker)); // “Ann”

delete marker; // if marker is GC’ed, it’s removed from WeakMap too!
Destructuring assignment
Destructuring: arrays

// for arrays
let [x, y] = [10, 20, 30];

console.log(x, y); // 10, 20
Destructuring of
           function parameters

function Panel(config) {
  var title = config.title;
  var x = config.pos[0];        Too “noisy”
  var y = config.pos[1];
  return title + x + y;
}
new Panel({title: “Users”, pos: [10, 15]});
Destructuring of
            function parameters

function Panel({title: title, pos: [x, y]}) {
  return title + x + y;
}

let config = {title: “Users”, pos: [10, 15]};

new Panel(config);
Eliminating of arguments:
     ...rest operator
Object arguments
// ES3, ES5

function format(pattern /*, rest */) {
  var rest = [].slice.call(arguments, 1);
  var items = rest.filter(function (x) { return x > 1});
  return pattern.replace(“%v”, items);
}

format(“scores: %v”, 1, 5, 3); // scores: 5, 3
Complicated arguments
// ES3, ES5

function format(pattern /*, rest */) {
  var rest = [].slice.call(arguments, 1); // complicated
  var items = rest.filter(function (x) { return x > 1});
  return pattern.replace(“%v”, items);
}

format(“scores: %v”, 1, 5, 3); // scores: 5, 3
...rest
// ES6 aka Harmony

function format(pattern, …rest) { // real array
  var items = rest.filter(function (x) { return x > 1});
  return pattern.replace(“%v”, items);
}

format(“scores: %v”, 1, 5, 3); // scores: 5, 3
Proxy objects : meta level
Proxy-objects

/* target – original object
 * handler – meta-handler */
Proxy(target, handler)
See: http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies



Note: old semantics (currently is implemented in Firefox) will not longer be available:
Proxy.create(handler, [proto]), Proxy.createFunction(handler, [call, [consruct]])
See: http://wiki.ecmascript.org/doku.php?id=harmony:proxies
Proxy-objects
 // original object       // proxied object
 let point = {            let loggedPoint = Proxy(point, {
    x: 10,                    get: function (point, name, rcvr) {
    y: 20                        console.log(“get: ”, name);
 };                              return point[name];
                              },
                              set: function (point, name, value, rcvr) {
Trap of getting of               console.log(“set: ”, name, value);
   properties
                                 point[name] = value;
                              }
Trap of setting the       });
    properties
Proxy-objects
                                    // proxied object
    Meta-handler                    let loggedPoint = Proxy(point, {
                                        get: function (point, name, rcvr) {
// reading trap                            console.log(“get: ”, name);
loggedPoint.x; // get: x, 10               return point[name];
                                        },
// writing trap                         set: function (point, name, value, rcvr) {
loggedPoint.x = 20; // set: x, 20          console.log(“set: ”, name, value);
                                           point[name] = value;
// reflected on the original object     }
point.x; // 20                      });
Struct types
Struct types
// struct types
let Point2D = new StructType({ x: uint32, y: uint32 });
let Color = new StructType({ r: uint8, g: uint8, b: uint8 });
let Pixel = new StructType({ point: Point2D, color: Color });

// array types
let Triangle = new ArrayType(Pixel, 3);

// dense-objects, based on struct binary types
let t = new Triangle([
    { point: { x: 0, y: 0 }, color: { r: 255, g: 255, b: 255 } },
    { point: { x: 5, y: 5 }, color: { r: 128, g: 0, b: 0 } },
    { point: { x: 10, y: 0 }, color: { r: 0, g: 0, b: 128 } }
]);
Struct types : example

// struct types
let IODataBlock = new StructType( /* attributes */ );

stream.read(IODataBlock, function (block) {
    // partial handling
});
Thanks for your attention


     Dmitry Soshnikov

dmitry.soshnikov@gmail.com
  http://dmitrysoshnikov.com

      @DmitrySoshnikov

Mais conteúdo relacionado

Mais procurados

Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheeltcurdt
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладкаDEVTYPE
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6FITC
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickHermann Hueck
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineMovel
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системеDEVTYPE
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveEugene Zharkov
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - GuilinJackson Tian
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 

Mais procurados (20)

Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 

Destaque

ttyrecからGIFアニメを作る話
ttyrecからGIFアニメを作る話ttyrecからGIFアニメを作る話
ttyrecからGIFアニメを作る話Yoshihiro Sugi
 
Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1Vasya Petrov
 
AddConf. Дмитрий Сошников - Будущее ECMAScript
AddConf. Дмитрий Сошников  - Будущее ECMAScriptAddConf. Дмитрий Сошников  - Будущее ECMAScript
AddConf. Дмитрий Сошников - Будущее ECMAScriptDmitry Soshnikov
 
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24MoscowJS
 
Обзор ES2015(ES6)
Обзор ES2015(ES6)Обзор ES2015(ES6)
Обзор ES2015(ES6)Alex Filatov
 
DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6Dmitry Soshnikov
 
JavaScript-модули "из прошлого в будущее"
JavaScript-модули "из прошлого в будущее"JavaScript-модули "из прошлого в будущее"
JavaScript-модули "из прошлого в будущее"oelifantiev
 
Ecma script 6 in action
Ecma script 6 in actionEcma script 6 in action
Ecma script 6 in actionYuri Trukhin
 
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24MoscowJS
 
Дэвид Флэнаган — Javascript (5 издание)
Дэвид Флэнаган — Javascript (5 издание)Дэвид Флэнаган — Javascript (5 издание)
Дэвид Флэнаган — Javascript (5 издание)mlatushko
 
altJSの選び方
altJSの選び方altJSの選び方
altJSの選び方terurou
 
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)Ontico
 
Keypoints html5
Keypoints html5Keypoints html5
Keypoints html5dynamis
 
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)Ontico
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraAllen Wirfs-Brock
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionMoscowJS
 
altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」政樹 尾野
 
1億5000万円欲しい (ロト6のデータで遊ぶ)
1億5000万円欲しい (ロト6のデータで遊ぶ)1億5000万円欲しい (ロト6のデータで遊ぶ)
1億5000万円欲しい (ロト6のデータで遊ぶ)Takuma Hatano
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptWojciech Dzikowski
 

Destaque (20)

ttyrecからGIFアニメを作る話
ttyrecからGIFアニメを作る話ttyrecからGIFアニメを作る話
ttyrecからGIFアニメを作る話
 
Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1
 
AddConf. Дмитрий Сошников - Будущее ECMAScript
AddConf. Дмитрий Сошников  - Будущее ECMAScriptAddConf. Дмитрий Сошников  - Будущее ECMAScript
AddConf. Дмитрий Сошников - Будущее ECMAScript
 
доклад
докладдоклад
доклад
 
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
 
Обзор ES2015(ES6)
Обзор ES2015(ES6)Обзор ES2015(ES6)
Обзор ES2015(ES6)
 
DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6
 
JavaScript-модули "из прошлого в будущее"
JavaScript-модули "из прошлого в будущее"JavaScript-модули "из прошлого в будущее"
JavaScript-модули "из прошлого в будущее"
 
Ecma script 6 in action
Ecma script 6 in actionEcma script 6 in action
Ecma script 6 in action
 
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
 
Дэвид Флэнаган — Javascript (5 издание)
Дэвид Флэнаган — Javascript (5 издание)Дэвид Флэнаган — Javascript (5 издание)
Дэвид Флэнаган — Javascript (5 издание)
 
altJSの選び方
altJSの選び方altJSの選び方
altJSの選び方
 
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
 
Keypoints html5
Keypoints html5Keypoints html5
Keypoints html5
 
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in action
 
altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」
 
1億5000万円欲しい (ロト6のデータで遊ぶ)
1億5000万円欲しい (ロト6のデータで遊ぶ)1億5000万円欲しい (ロト6のデータで遊ぶ)
1億5000万円欲しい (ロト6のデータで遊ぶ)
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 

Semelhante a HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervosoLuis Vendrame
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriverchristkv
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessorAlessandro Nadalin
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suckerockendude
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montageKris Kowal
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+ConFoo
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 

Semelhante a HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6 (20)

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessor
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 

Último

Leveraging USDA Rural Development Grants for Community Growth and Sustainabil...
Leveraging USDA Rural Development Grants for Community Growth and Sustainabil...Leveraging USDA Rural Development Grants for Community Growth and Sustainabil...
Leveraging USDA Rural Development Grants for Community Growth and Sustainabil...USDAReapgrants.com
 
Osisko Gold Royalties Ltd - Corporate Presentation, April 10, 2024
Osisko Gold Royalties Ltd - Corporate Presentation, April 10, 2024Osisko Gold Royalties Ltd - Corporate Presentation, April 10, 2024
Osisko Gold Royalties Ltd - Corporate Presentation, April 10, 2024Osisko Gold Royalties Ltd
 
Collective Mining | Corporate Presentation - April 2024
Collective Mining | Corporate Presentation - April 2024Collective Mining | Corporate Presentation - April 2024
Collective Mining | Corporate Presentation - April 2024CollectiveMining1
 
slideshare_2404_presentation materials_en.pdf
slideshare_2404_presentation materials_en.pdfslideshare_2404_presentation materials_en.pdf
slideshare_2404_presentation materials_en.pdfsansanir
 
Q1 Quarterly Update - April 16, 2024.pdf
Q1 Quarterly Update - April 16, 2024.pdfQ1 Quarterly Update - April 16, 2024.pdf
Q1 Quarterly Update - April 16, 2024.pdfProbe Gold
 
Mandalay Resources 2024 April IR Presentation
Mandalay Resources 2024 April IR PresentationMandalay Resources 2024 April IR Presentation
Mandalay Resources 2024 April IR PresentationMandalayResources
 
Corporate Presentation Probe April 2024.pdf
Corporate Presentation Probe April 2024.pdfCorporate Presentation Probe April 2024.pdf
Corporate Presentation Probe April 2024.pdfProbe Gold
 
Q1 Probe Gold Quarterly Update- April 2024
Q1 Probe Gold Quarterly Update- April 2024Q1 Probe Gold Quarterly Update- April 2024
Q1 Probe Gold Quarterly Update- April 2024Probe Gold
 
the 25 most beautiful words for a loving and lasting relationship.pdf
the 25 most beautiful words for a loving and lasting relationship.pdfthe 25 most beautiful words for a loving and lasting relationship.pdf
the 25 most beautiful words for a loving and lasting relationship.pdfFrancenel
 
Collective Mining | Corporate Presentation | April 2024
Collective Mining | Corporate Presentation | April 2024Collective Mining | Corporate Presentation | April 2024
Collective Mining | Corporate Presentation | April 2024CollectiveMining1
 
Corporate Presentation Probe April 2024.pdf
Corporate Presentation Probe April 2024.pdfCorporate Presentation Probe April 2024.pdf
Corporate Presentation Probe April 2024.pdfProbe Gold
 

Último (12)

Leveraging USDA Rural Development Grants for Community Growth and Sustainabil...
Leveraging USDA Rural Development Grants for Community Growth and Sustainabil...Leveraging USDA Rural Development Grants for Community Growth and Sustainabil...
Leveraging USDA Rural Development Grants for Community Growth and Sustainabil...
 
Osisko Gold Royalties Ltd - Corporate Presentation, April 10, 2024
Osisko Gold Royalties Ltd - Corporate Presentation, April 10, 2024Osisko Gold Royalties Ltd - Corporate Presentation, April 10, 2024
Osisko Gold Royalties Ltd - Corporate Presentation, April 10, 2024
 
Collective Mining | Corporate Presentation - April 2024
Collective Mining | Corporate Presentation - April 2024Collective Mining | Corporate Presentation - April 2024
Collective Mining | Corporate Presentation - April 2024
 
slideshare_2404_presentation materials_en.pdf
slideshare_2404_presentation materials_en.pdfslideshare_2404_presentation materials_en.pdf
slideshare_2404_presentation materials_en.pdf
 
Q1 Quarterly Update - April 16, 2024.pdf
Q1 Quarterly Update - April 16, 2024.pdfQ1 Quarterly Update - April 16, 2024.pdf
Q1 Quarterly Update - April 16, 2024.pdf
 
Mandalay Resources 2024 April IR Presentation
Mandalay Resources 2024 April IR PresentationMandalay Resources 2024 April IR Presentation
Mandalay Resources 2024 April IR Presentation
 
Corporate Presentation Probe April 2024.pdf
Corporate Presentation Probe April 2024.pdfCorporate Presentation Probe April 2024.pdf
Corporate Presentation Probe April 2024.pdf
 
Q1 Probe Gold Quarterly Update- April 2024
Q1 Probe Gold Quarterly Update- April 2024Q1 Probe Gold Quarterly Update- April 2024
Q1 Probe Gold Quarterly Update- April 2024
 
the 25 most beautiful words for a loving and lasting relationship.pdf
the 25 most beautiful words for a loving and lasting relationship.pdfthe 25 most beautiful words for a loving and lasting relationship.pdf
the 25 most beautiful words for a loving and lasting relationship.pdf
 
Korea District Heating Corporation 071320 Algorithm Investment Report
Korea District Heating Corporation 071320 Algorithm Investment ReportKorea District Heating Corporation 071320 Algorithm Investment Report
Korea District Heating Corporation 071320 Algorithm Investment Report
 
Collective Mining | Corporate Presentation | April 2024
Collective Mining | Corporate Presentation | April 2024Collective Mining | Corporate Presentation | April 2024
Collective Mining | Corporate Presentation | April 2024
 
Corporate Presentation Probe April 2024.pdf
Corporate Presentation Probe April 2024.pdfCorporate Presentation Probe April 2024.pdf
Corporate Presentation Probe April 2024.pdf
 

HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6

  • 1. @HelsinkiJS meet-up December 12, 2011 ECMAScript, 6 Dmitry Soshnikov http://dmitrysoshnikov.com
  • 2. Function parameter default values
  • 3. Function parameter default values function handleRequest(data, method) { method = method || “GET”; ... }
  • 4. Function parameter default values function handleRequest(data, method) { method = method || “GET”; ... } function handleRequest(data, method = “GET”) { ... }
  • 6. Modules in ES3, ES5 var DBLayer = (function (global) { /* save original */ var originalDBLayer = global.DBLayer; function noConflict() { global.DBLayer = originalDBLayer; 1. Create local scope } 2. Restoring function /* implementation */ 3. Implementation 4. Public API function query() { ... } /* exports, public API */ return { noConflict: noConflict, query: query }; })(this);
  • 7. Modules in ES3, ES5 var DBLayer = (function (global) { /* save original */ var originalDBLayer = global.DBLayer; function noConflict() { global.DBLayer = originalDBLayer; 1. Create local scope } 2. Restoring function /* implementation */ 3. Implementation 4. Public API function query() { ... } /* exports, public API */ Too much of “noise”. return { A “sugar” is needed. noConflict: noConflict, query: query }; })(this);
  • 8. Modules in ES6 module DBLayer { export function query(s) { ... } export function connection(...args) { ... } } import * from DBLayer; // import all // import only needed exports import {query, connection: attachTo} from DBLayer query(“SELECT * FROM books”).format(“escape | split”); attachTo(“/books/store”, { onSuccess: function (response) { ... } })
  • 10. Quasis : string templates let content = “<a href=‘” + url + “’ title=‘” + title + “’>” + text+ “</a>”; $(“#bar”).html(content);
  • 11. Quasis : string templates let content = “<a href=‘” + url + “’ title=‘” + title + “’>” + text+ “</a>”; $(“#bar”).html(content); let content = safeHtml `<a href=“${url} “ title=“${title}”>${text}</a>`; $(“#bar”).html(content); See: http://wiki.ecmascript.org/doku.php?id=harmony:quasis
  • 13. Array comprehensions // map + filter way let scores = [1, 7, 4, 9] .filter(function (x) { return x > 5 }) .map(function (x) { return x * x }); // [49, 81]
  • 14. Array comprehensions // map + filter way let scores = [1, 7, 4, 9] .filter(function (x) { return x > 5 }) .map(function (x) { return x * x }); // [49, 81] // array comprehensions let scores = [x * x for (x in values([1, 7, 4, 9])) if (x > 5)];
  • 16. Map and WeakMap let user = {name: “Ann”, x: 10, y: 20}; // Keys in a map are objects let scoresMap = new Map; map.set(user, 100); console.log(scoresMap.get(user)); // 100
  • 17. Map and WeakMap let user = {name: “Ann”, x: 10, y: 20}; // Keys in a map are objects let scoresMap = new Map; map.set(user, 100); console.log(scoresMap.get(user)); // 100 let markers = new WeakMap; marker = new Marker(10, 20); markers.set(marker, “Ann”); console.log(weakMap.get(marker)); // “Ann” delete marker; // if marker is GC’ed, it’s removed from WeakMap too!
  • 19. Destructuring: arrays // for arrays let [x, y] = [10, 20, 30]; console.log(x, y); // 10, 20
  • 20. Destructuring of function parameters function Panel(config) { var title = config.title; var x = config.pos[0]; Too “noisy” var y = config.pos[1]; return title + x + y; } new Panel({title: “Users”, pos: [10, 15]});
  • 21. Destructuring of function parameters function Panel({title: title, pos: [x, y]}) { return title + x + y; } let config = {title: “Users”, pos: [10, 15]}; new Panel(config);
  • 22. Eliminating of arguments: ...rest operator
  • 23. Object arguments // ES3, ES5 function format(pattern /*, rest */) { var rest = [].slice.call(arguments, 1); var items = rest.filter(function (x) { return x > 1}); return pattern.replace(“%v”, items); } format(“scores: %v”, 1, 5, 3); // scores: 5, 3
  • 24. Complicated arguments // ES3, ES5 function format(pattern /*, rest */) { var rest = [].slice.call(arguments, 1); // complicated var items = rest.filter(function (x) { return x > 1}); return pattern.replace(“%v”, items); } format(“scores: %v”, 1, 5, 3); // scores: 5, 3
  • 25. ...rest // ES6 aka Harmony function format(pattern, …rest) { // real array var items = rest.filter(function (x) { return x > 1}); return pattern.replace(“%v”, items); } format(“scores: %v”, 1, 5, 3); // scores: 5, 3
  • 26. Proxy objects : meta level
  • 27. Proxy-objects /* target – original object * handler – meta-handler */ Proxy(target, handler) See: http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies Note: old semantics (currently is implemented in Firefox) will not longer be available: Proxy.create(handler, [proto]), Proxy.createFunction(handler, [call, [consruct]]) See: http://wiki.ecmascript.org/doku.php?id=harmony:proxies
  • 28. Proxy-objects // original object // proxied object let point = { let loggedPoint = Proxy(point, { x: 10, get: function (point, name, rcvr) { y: 20 console.log(“get: ”, name); }; return point[name]; }, set: function (point, name, value, rcvr) { Trap of getting of console.log(“set: ”, name, value); properties point[name] = value; } Trap of setting the }); properties
  • 29. Proxy-objects // proxied object Meta-handler let loggedPoint = Proxy(point, { get: function (point, name, rcvr) { // reading trap console.log(“get: ”, name); loggedPoint.x; // get: x, 10 return point[name]; }, // writing trap set: function (point, name, value, rcvr) { loggedPoint.x = 20; // set: x, 20 console.log(“set: ”, name, value); point[name] = value; // reflected on the original object } point.x; // 20 });
  • 31. Struct types // struct types let Point2D = new StructType({ x: uint32, y: uint32 }); let Color = new StructType({ r: uint8, g: uint8, b: uint8 }); let Pixel = new StructType({ point: Point2D, color: Color }); // array types let Triangle = new ArrayType(Pixel, 3); // dense-objects, based on struct binary types let t = new Triangle([ { point: { x: 0, y: 0 }, color: { r: 255, g: 255, b: 255 } }, { point: { x: 5, y: 5 }, color: { r: 128, g: 0, b: 0 } }, { point: { x: 10, y: 0 }, color: { r: 0, g: 0, b: 128 } } ]);
  • 32. Struct types : example // struct types let IODataBlock = new StructType( /* attributes */ ); stream.read(IODataBlock, function (block) { // partial handling });
  • 33. Thanks for your attention Dmitry Soshnikov dmitry.soshnikov@gmail.com http://dmitrysoshnikov.com @DmitrySoshnikov