SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
@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

Contenu connexe

Tendances

Tendances (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
 

En vedette

AddConf. Дмитрий Сошников - Будущее ECMAScript
AddConf. Дмитрий Сошников  - Будущее ECMAScriptAddConf. Дмитрий Сошников  - Будущее ECMAScript
AddConf. Дмитрий Сошников - Будущее ECMAScript
Dmitry Soshnikov
 
DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6
Dmitry Soshnikov
 
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Ontico
 
altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」
政樹 尾野
 

En vedette (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
 

Similaire à HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6

Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
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
erockendude
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
Kris 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
 

Similaire à 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
 

Dernier

Ambala Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Ambala Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...Ambala Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Ambala Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
mriyagarg453
 
💚😋 jamshedpur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 jamshedpur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 jamshedpur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 jamshedpur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
nirzagarg
 
Editing progress 20th march.docxxxxxxxxx
Editing progress 20th march.docxxxxxxxxxEditing progress 20th march.docxxxxxxxxx
Editing progress 20th march.docxxxxxxxxx
MollyBrown86
 
Corporate Presentation Probe Canaccord Conference 2024.pdf
Corporate Presentation Probe Canaccord Conference 2024.pdfCorporate Presentation Probe Canaccord Conference 2024.pdf
Corporate Presentation Probe Canaccord Conference 2024.pdf
Probe Gold
 
VIP Call Girls Kheda 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Kheda 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Kheda 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Kheda 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Top Rated Call Girls In Podanur 📱 {7001035870} VIP Escorts Podanur
Top Rated Call Girls In Podanur 📱 {7001035870} VIP Escorts PodanurTop Rated Call Girls In Podanur 📱 {7001035870} VIP Escorts Podanur
Top Rated Call Girls In Podanur 📱 {7001035870} VIP Escorts Podanur
dharasingh5698
 
Terna - 1Q 2024 Consolidated Results Presentation
Terna - 1Q 2024 Consolidated Results PresentationTerna - 1Q 2024 Consolidated Results Presentation
Terna - 1Q 2024 Consolidated Results Presentation
Terna SpA
 
VIP Call Girls Mehsana 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Mehsana 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Mehsana 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Mehsana 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 

Dernier (20)

AMG Quarterly Investor Presentation May 2024
AMG Quarterly Investor Presentation May 2024AMG Quarterly Investor Presentation May 2024
AMG Quarterly Investor Presentation May 2024
 
Dubai Call Girls O525547&19 Calls Girls In Dubai (L0w+Charger)
Dubai Call Girls O525547&19 Calls Girls In Dubai (L0w+Charger)Dubai Call Girls O525547&19 Calls Girls In Dubai (L0w+Charger)
Dubai Call Girls O525547&19 Calls Girls In Dubai (L0w+Charger)
 
Ambala Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Ambala Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...Ambala Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Ambala Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
 
Teekay Tankers Q1-24 Earnings Presentation
Teekay Tankers Q1-24 Earnings PresentationTeekay Tankers Q1-24 Earnings Presentation
Teekay Tankers Q1-24 Earnings Presentation
 
Best investment platform in india-Falcon Invoice Discounting
Best investment platform in india-Falcon Invoice DiscountingBest investment platform in india-Falcon Invoice Discounting
Best investment platform in india-Falcon Invoice Discounting
 
High Profile Call Girls in Pune (Adult Only) 8005736733 Escort Service 24x7 ...
High Profile Call Girls in Pune  (Adult Only) 8005736733 Escort Service 24x7 ...High Profile Call Girls in Pune  (Adult Only) 8005736733 Escort Service 24x7 ...
High Profile Call Girls in Pune (Adult Only) 8005736733 Escort Service 24x7 ...
 
Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024
 
countries with the highest gold reserves in 2024
countries with the highest gold reserves in 2024countries with the highest gold reserves in 2024
countries with the highest gold reserves in 2024
 
💚😋 jamshedpur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 jamshedpur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 jamshedpur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 jamshedpur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
 
Editing progress 20th march.docxxxxxxxxx
Editing progress 20th march.docxxxxxxxxxEditing progress 20th march.docxxxxxxxxx
Editing progress 20th march.docxxxxxxxxx
 
Corporate Presentation Probe Canaccord Conference 2024.pdf
Corporate Presentation Probe Canaccord Conference 2024.pdfCorporate Presentation Probe Canaccord Conference 2024.pdf
Corporate Presentation Probe Canaccord Conference 2024.pdf
 
VIP Call Girls Kheda 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Kheda 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Kheda 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Kheda 7001035870 Whatsapp Number, 24/07 Booking
 
Diligence Checklist for Early Stage Startups
Diligence Checklist for Early Stage StartupsDiligence Checklist for Early Stage Startups
Diligence Checklist for Early Stage Startups
 
VVIP Pune Call Girls Sopan Baug WhatSapp Number 8005736733 With Elite Staff A...
VVIP Pune Call Girls Sopan Baug WhatSapp Number 8005736733 With Elite Staff A...VVIP Pune Call Girls Sopan Baug WhatSapp Number 8005736733 With Elite Staff A...
VVIP Pune Call Girls Sopan Baug WhatSapp Number 8005736733 With Elite Staff A...
 
Top Rated Call Girls In Podanur 📱 {7001035870} VIP Escorts Podanur
Top Rated Call Girls In Podanur 📱 {7001035870} VIP Escorts PodanurTop Rated Call Girls In Podanur 📱 {7001035870} VIP Escorts Podanur
Top Rated Call Girls In Podanur 📱 {7001035870} VIP Escorts Podanur
 
Terna - 1Q 2024 Consolidated Results Presentation
Terna - 1Q 2024 Consolidated Results PresentationTerna - 1Q 2024 Consolidated Results Presentation
Terna - 1Q 2024 Consolidated Results Presentation
 
Vijayawada ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready F...
Vijayawada ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready F...Vijayawada ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready F...
Vijayawada ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready F...
 
VVIP Pune Call Girls Handewadi WhatSapp Number 8005736733 With Elite Staff An...
VVIP Pune Call Girls Handewadi WhatSapp Number 8005736733 With Elite Staff An...VVIP Pune Call Girls Handewadi WhatSapp Number 8005736733 With Elite Staff An...
VVIP Pune Call Girls Handewadi WhatSapp Number 8005736733 With Elite Staff An...
 
VIP Call Girls Mehsana 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Mehsana 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Mehsana 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Mehsana 7001035870 Whatsapp Number, 24/07 Booking
 
Teekay Corporation Q1-24 Earnings Results
Teekay Corporation Q1-24 Earnings ResultsTeekay Corporation Q1-24 Earnings Results
Teekay Corporation Q1-24 Earnings Results
 

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