SlideShare una empresa de Scribd logo
1 de 42
Descargar para leer sin conexión
Javascript
New features (only some)
- let / const
- arrow functions
- for..of loops
- tail call optimisation
- default function parameters
- rest parameters / spread operator
- object literal extensions
- computed properties
- shorthand properties/methods
- computed shorthand methods / computed
accessors
- template strings (+ tagged
functions)
- destructuring
- class
- generators
- Map / Set
- async / await (ES7 - stage 3)
- Object.observe (ES7 - stage 2)
- Observables (ES7 - stage 1)
- class and property decorators
(ES7 - stage 1)
let - block scope variable declaration
- block scope variable declaration
if(true) {
let x = 1;
}
console.log(x); // ReferenceError: x is not defined
for(let val of [1, 2, 3, 5]) {
/*...*/
}
console.log(val); // ReferenceError: val is not defined
let - block scope variable declaration
- does not hoist (TDZ)
if(true) {
console.log(x); // ReferenceError: foo is not defined
let x = 42;
}
const
- similar to let
- must be initialized on declaration
const x; // SyntaxError: missing = in const declaration
- fail silently on reassignment (firefox and chrome)
const x = 1;
x = -1; // fails silently
- throws error on redeclaration
const x = 3.14159;
const x = 2.71828; // TypeError: redeclaration of const x
arrow functions - improved syntax
let inc = function(a) { return a + 1; };
let sum = function(a, b) { return a + b; };
let arr = [1, 2, 3, 7, 22];
arr.map(function(n) { return n + 2; })
.filter(function(n) { return n > 8; });
let inc = a => a + 1;
let sum = (a, b) => a + b;
let arr = [1, 2, 3, 7, 22];
arr.map(n => n + 2).filter(n => n > 8);
arrow functions - lexical “this”
<button id="btn">Click</button>
<script>
function Widget() {
this.clickCounter = 0; // (1)
document.querySelector('#btn').addEventListener('click', function() {
this.clickCounter++; // “this” here is different from “this” on line (1)
console.log(this.clickCounter);
});
};
var mywidget = new Widget();
</script>
arrow functions - lexical “this”
<button id="btn">Click</button>
<script>
function Widget() {
this.clickCounter = 0;
var self = this;
document.querySelector('#btn').addEventListener('click', function() {
self.clickCounter++; // use “self” instead of “this”
console.log(this.clickCounter);
});
};
var mywidget = new Widget();
</script>
arrow functions - lexical “this”
<button id="btn">Click</button>
<script>
function Widget() {
this.clickCounter = 0; // (1)
document.querySelector('#btn').addEventListener('click', () => {
this.clickCounter++; // “this” here is the same as “this” from line (1)
console.log(this.clickCounter);
});
};
var mywidget = new Widget();
</script>
arrow functions - nice for higher order functions
let notEquals = function(a) {
return function(b) {
return a !== b;
}
};
let notEquals = a => b => a === b;
[2, 3, 5, 7, 11].filter(notEquals(5)); // [2, 3, 7, 11]
// notEquals(5) == b => 5 !== b
for...of loops
- iterates over values
let arr = [2, 7, 1, 8, 2, 8];
for(let index in arr) {
console.log(index); // 0, 1, 2, 3, 4, 5
}
for(let value of arr) {
console.log(value); // 2, 7, 1, 8, 2, 8
}
tail call optimisation
- tail call is when the last thing a function does is to call another function
- it reuses the current stack frame
- it encourages the use of recursive functions and generally programming in a
functional style
default function parameters
function fuu(a, b = 1) {
console.log(‘a =’, a, ‘;‘, ‘b =’, b);
}
fuu(); // a = undefined; b = 1
fuu(2); // a = 2; b = 1
fuu(2, 3); // a = 2; b = 3
rest parameters
- accumulate the rest of the parameters from a function call
function baar(a, b, ...c) {
console.log(a, b, c);
}
baar(1); // 1 undefined Array[ ]
baar(1, 4); // 1 4 Array[ ]
baar(1, 4, 11); // 1 4 Array[11]
baar(1, 4, 11, 30); // 1 4 Array[11, 30]
spread operator
- expands an iterator where multiple values are expected
fn(...[1, 2, 3]); // equivalent to fn(1, 2, 3)
fn(1, 2, …[7, 41]); // equivalent to fn(1, 2, 7, 41)
let a = [1, 2], b = [4, 5, 6];
let c = [3, 4, ...a]; // c = [3, 4, 1, 2]
let d = [...a, ...b]; // d = [1, 2, 4, 5, 6]
object literal extensions
- computed properties
let a = ‘b’;
let c = {
[a]: 4,
[‘a’ + a + ‘c’]: 5
};
console.log(c.b); // 4
console.log(c.abc); // 5
object literal extensions
- shorthand properties
let x = 1, y = 2;
let obj;
obj = {x, y, z: 3}; // equivalent to “obj = {x: x, y: y, z: 3}”
- shorthand methods
obj = { sum(a, b) { return a + b; } }
obj.sum(6, 11); // 17
object literal extensions
- computed shorthand methods
let myMethod = ‘sum’;
let obj = { [myMethod](a, b) { return a + b; } };
obj.sum(6, 11); // 17
template strings
let s = `just made you read this`;
let five = 5,
t = `2 + 2 is ${2 + 2} not ${five}`;
// multiline
let criticilor = `Critici voi, cu flori desarte,
Care roade n-ati adus
E usor a scrie versuri
Când nimic nu ai de spus.
(Mihai Eminescu)`;
template strings - tag functions
function mytag(strings, ...values) {
console.log(strings[0]); // “roses are not “
console.log(strings[1]); // “, violets are not “
console.log(values[0]); // “blue”
console.log(values[1]); // “red”
return ‘anything you want’;
}
let r = ‘red’, b = ‘blu’;
mytag`roses are not ${b + ‘e’}, violets are not ${r}`; // ”anything you want”
destructuring
let [a, b, c] = [-1, -2, -3];
console.log(‘a =’, a, ‘b =’, b, ‘d !=’, c); // a = -1 b = -2 d != -3
let [ , , d] = [4, 5, -6];
console.log(‘d =’, d); // d = -6
let [e, [f, [g]]] = [7, [8, [9]]];
let [first, ...rest] = [‘first’, ‘r’, ‘e’, ‘s’, ‘t’];
console.log(‘first =‘, first, ‘rest =’, rest); // first = ‘first’ rest = [‘r’, ‘e’, ‘s’, ‘t’]
let {name: theName, age} = {name: ‘4real Superman Wheaton’, age: 31};
console.log(‘name =’, theName); // name = “4real Superman Wheaton”
console.log(‘age =’, age); // age = 31
let nested = {very: [‘little’, {baby: ‘bird’}] },
{very: [little, {baby}] } = nested;
console.log(‘little =’, little, ‘baby =’, bird); // little = “little” baby = “bird”
let [a = 1, b = 2] = [3]; // a = 3, b = 2
let {w: y = ‘z’} = {v: ‘v’}; // y = ‘z’
destructuring
function http({url, method, data}) {
fetch(url, {method, body: data}).then(response => alert(response));
}
http({url: ‘http://com.net’, method: ‘post’, data: {id: ‘di’, name: ‘ne im’}});
destructuring
- syntactic sugar over prototypal inheritance
- fundamentally they are functions and just as functions they can have both
forms (as declarations and as expressions)
class
class declaration
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class expression
let Point = class {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(p, q) {
return Math.sqrt((p.x - q.x) ** 2 + (p.y - q.y) ** 2 );
}
}
console.log(new Point(1, 1), new Point(5, 4)); // 5
class - static keyword
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y);
this.color = color;
}
}
let cp = new ColorPoint(1, 1, ‘green’));
class - extends and super keywords
- generators are functions which can be exited and later re-entered
- their context (variable bindings) will be saved across re-entrances
- returns an iterator
function* idMaker() {
let index = 0;
while(index < 3) yield index++;
}
let gen = idMaker();
console.log(gen.next()); // {value: 0, done: false}
console.log(gen.next()); // {value: 1, done: false}
console.log(gen.next()); // {value: 2, done: false}
console.log(gen.next()); // {value: undefined, done: true}
generators
- yield* delegates to another generator function
function* generator(i) {
yield i;
yield* idMaker(i);
yield i + 10;
}
let gen = generator(10);
console.log(gen.next()); // {value: 10, done: false}
console.log(gen.next()); // {value: 0, done: false}
console.log(gen.next()); // {value: 1, done: false}
console.log(gen.next()); // {value: 2, done: false}
console.log(gen.next()); // {value: 20, done: false}
console.log(gen.next()); // {value: undefined, done: true}
generators
Differences between objects and maps:
● An Object has a prototype, so there are default keys in the map. This could
be bypassed by using map = Object.create(null) since ES5, but was
seldomly done.
● The keys of an Object are Strings and Symbols, where they can be any
value for a Map.
● You can get the size of a Map easily while you have to manually keep track
of size for an Object.
Map - new Map([iterable])
- the Set object lets you store unique values of any type, whether primitive
values or object references.
- you can iterate its elements in insertion order
Set - new Set([iterable]);
- asynchronous code written in a synchronous manner
- syntactic sugar over generators
function getAPromise() {
return new Promise(resolve => setTimeout(() => resolve(‘hello!’), 3000));
}
async function doStuff() {
let value = await getAPromise();
console.log(‘value of the promise is’, value);
}
doStuff(); // value of the promise is hello!
async/await - ES7 (stage 3)
function getData(url) {
return fetch(url);
}
(async function() {
let urls = [‘users/1’, ‘users/2’, ‘users/3’];
for(let data of urls.map(getData)) { // makes requests in parallel
console.log((await data).name); // logs the user names in order
}
}());
async/await - ES7 (stage 3)
- asynchronously observing the changes to an object
- it provides a stream of changes in the order in which they occur
let obj = {foo: 0, bar: 1};
Object.observe(obj, function(changes) {
console.log(changes);
});
obj.baz = 2; // [{name: 'baz', object: <obj>, type: 'add'}]
obj.foo = 'hello'; // [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}]
delete obj.baz; // [{name: 'baz', object: <obj>, type: 'delete', oldValue: 2}]
Object.defineProperty(obj, 'foo', {writable: false});
// [{name: 'foo', object: <obj>, type: 'reconfigure'}]
Object.observe - ES7 (stage 2)
- proposal for an Observable type
- used to model push-based data sources such as DOM events, timer
intervals, sockets and others
- can be composed with higher-order combinators
- they do not start emitting data until an observer has subscribed
Observables - ES7 (stage 1)
function listen(element, eventName) {
return new Observable(observer => {
// Create an event handler which sends data to the observer
let handler = event => observer.next(event);
// Attach the event handler
element.addEventListener(eventName, handler, true);
});
}
Observables - ES7 (stage 1)
// Return an observable of special key down commands
function commandKeys(element) {
let keyCommands = { "38": "up", "40": "down" };
return listen(element, "keydown")
.filter(event => event.keyCode in keyCommands)
.map(event => keyCommands[event.keyCode])
}
commandKeys(inputElement).subscribe({
next(val) { console.log("Received key command: " + val) }, // “up” “down” “up” “up” “down” “up”
// error(err) { console.log("Received an error: " + err) },
// complete() { console.log("Stream complete") }
});
Observables - ES7 (stage 1)
A decorator is:
- an expression
- that evaluates to a function
- that takes the target, name, and property descriptor as arguments
- and optionally returns a property descriptor to install on the target object
class Person {
@nonenumerable
get kidCount() { return this.children.length; }
}
function nonenumerable(target, name, descriptor) {
descriptor.enumerable = false;
return descriptor;
}
class and property decorators - ES7 (stage 1)
- It is also possible to decorate the class itself. In this case, the decorator
takes the target constructor.
@annotation
class MyClass { }
function annotation(target) {
// Add a property on target
target.annotated = true;
}
class and property decorators - ES7 (stage 1)
- since decorators are expressions, decorators can take additional arguments
and act like a factory
class C {
@enumerable(false)
method() { }
}
function enumerable(value) {
return function (target, key, descriptor) {
descriptor.enumerable = value;
return descriptor;
}
}
class and property decorators - ES7 (stage 1)
FINally

Más contenido relacionado

La actualidad más candente

Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)David de Boer
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Calvin Cheng
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...tdc-globalcode
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBtdc-globalcode
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?jonbodner
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196Mahmoud Samir Fayed
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Webbeyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
beyond tellerrand: Mobile Apps with JavaScript – There's More Than WebHeiko Behrens
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwoEishay Smith
 
How fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceHow fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceTobias Pfeiffer
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overviewAveic
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, pythonRobert Lujo
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data StructureChan Shik Lim
 

La actualidad más candente (20)

Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
Intro
IntroIntro
Intro
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
C# 7
C# 7C# 7
C# 7
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Webbeyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
 
Awt
AwtAwt
Awt
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
Pdxpugday2010 pg90
Pdxpugday2010 pg90Pdxpugday2010 pg90
Pdxpugday2010 pg90
 
How fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceHow fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practice
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 

Similar a Javascript

HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 ReviewSperasoft
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScriptJosh Mock
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyondFrancis Johny
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskellujihisa
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
The hidden and new parts of JS
The hidden and new parts of JSThe hidden and new parts of JS
The hidden and new parts of JSRitesh Kumar
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 

Similar a Javascript (20)

ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskell
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
The hidden and new parts of JS
The hidden and new parts of JSThe hidden and new parts of JS
The hidden and new parts of JS
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 

Último

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 

Último (20)

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 

Javascript

  • 2.
  • 3.
  • 4. New features (only some) - let / const - arrow functions - for..of loops - tail call optimisation - default function parameters - rest parameters / spread operator - object literal extensions - computed properties - shorthand properties/methods - computed shorthand methods / computed accessors - template strings (+ tagged functions) - destructuring - class - generators - Map / Set - async / await (ES7 - stage 3) - Object.observe (ES7 - stage 2) - Observables (ES7 - stage 1) - class and property decorators (ES7 - stage 1)
  • 5. let - block scope variable declaration - block scope variable declaration if(true) { let x = 1; } console.log(x); // ReferenceError: x is not defined for(let val of [1, 2, 3, 5]) { /*...*/ } console.log(val); // ReferenceError: val is not defined
  • 6. let - block scope variable declaration - does not hoist (TDZ) if(true) { console.log(x); // ReferenceError: foo is not defined let x = 42; }
  • 7. const - similar to let - must be initialized on declaration const x; // SyntaxError: missing = in const declaration - fail silently on reassignment (firefox and chrome) const x = 1; x = -1; // fails silently - throws error on redeclaration const x = 3.14159; const x = 2.71828; // TypeError: redeclaration of const x
  • 8. arrow functions - improved syntax let inc = function(a) { return a + 1; }; let sum = function(a, b) { return a + b; }; let arr = [1, 2, 3, 7, 22]; arr.map(function(n) { return n + 2; }) .filter(function(n) { return n > 8; }); let inc = a => a + 1; let sum = (a, b) => a + b; let arr = [1, 2, 3, 7, 22]; arr.map(n => n + 2).filter(n => n > 8);
  • 9. arrow functions - lexical “this” <button id="btn">Click</button> <script> function Widget() { this.clickCounter = 0; // (1) document.querySelector('#btn').addEventListener('click', function() { this.clickCounter++; // “this” here is different from “this” on line (1) console.log(this.clickCounter); }); }; var mywidget = new Widget(); </script>
  • 10. arrow functions - lexical “this” <button id="btn">Click</button> <script> function Widget() { this.clickCounter = 0; var self = this; document.querySelector('#btn').addEventListener('click', function() { self.clickCounter++; // use “self” instead of “this” console.log(this.clickCounter); }); }; var mywidget = new Widget(); </script>
  • 11. arrow functions - lexical “this” <button id="btn">Click</button> <script> function Widget() { this.clickCounter = 0; // (1) document.querySelector('#btn').addEventListener('click', () => { this.clickCounter++; // “this” here is the same as “this” from line (1) console.log(this.clickCounter); }); }; var mywidget = new Widget(); </script>
  • 12. arrow functions - nice for higher order functions let notEquals = function(a) { return function(b) { return a !== b; } }; let notEquals = a => b => a === b; [2, 3, 5, 7, 11].filter(notEquals(5)); // [2, 3, 7, 11] // notEquals(5) == b => 5 !== b
  • 13. for...of loops - iterates over values let arr = [2, 7, 1, 8, 2, 8]; for(let index in arr) { console.log(index); // 0, 1, 2, 3, 4, 5 } for(let value of arr) { console.log(value); // 2, 7, 1, 8, 2, 8 }
  • 14. tail call optimisation - tail call is when the last thing a function does is to call another function - it reuses the current stack frame - it encourages the use of recursive functions and generally programming in a functional style
  • 15. default function parameters function fuu(a, b = 1) { console.log(‘a =’, a, ‘;‘, ‘b =’, b); } fuu(); // a = undefined; b = 1 fuu(2); // a = 2; b = 1 fuu(2, 3); // a = 2; b = 3
  • 16. rest parameters - accumulate the rest of the parameters from a function call function baar(a, b, ...c) { console.log(a, b, c); } baar(1); // 1 undefined Array[ ] baar(1, 4); // 1 4 Array[ ] baar(1, 4, 11); // 1 4 Array[11] baar(1, 4, 11, 30); // 1 4 Array[11, 30]
  • 17. spread operator - expands an iterator where multiple values are expected fn(...[1, 2, 3]); // equivalent to fn(1, 2, 3) fn(1, 2, …[7, 41]); // equivalent to fn(1, 2, 7, 41) let a = [1, 2], b = [4, 5, 6]; let c = [3, 4, ...a]; // c = [3, 4, 1, 2] let d = [...a, ...b]; // d = [1, 2, 4, 5, 6]
  • 18. object literal extensions - computed properties let a = ‘b’; let c = { [a]: 4, [‘a’ + a + ‘c’]: 5 }; console.log(c.b); // 4 console.log(c.abc); // 5
  • 19. object literal extensions - shorthand properties let x = 1, y = 2; let obj; obj = {x, y, z: 3}; // equivalent to “obj = {x: x, y: y, z: 3}” - shorthand methods obj = { sum(a, b) { return a + b; } } obj.sum(6, 11); // 17
  • 20. object literal extensions - computed shorthand methods let myMethod = ‘sum’; let obj = { [myMethod](a, b) { return a + b; } }; obj.sum(6, 11); // 17
  • 21. template strings let s = `just made you read this`; let five = 5, t = `2 + 2 is ${2 + 2} not ${five}`; // multiline let criticilor = `Critici voi, cu flori desarte, Care roade n-ati adus E usor a scrie versuri Când nimic nu ai de spus. (Mihai Eminescu)`;
  • 22. template strings - tag functions function mytag(strings, ...values) { console.log(strings[0]); // “roses are not “ console.log(strings[1]); // “, violets are not “ console.log(values[0]); // “blue” console.log(values[1]); // “red” return ‘anything you want’; } let r = ‘red’, b = ‘blu’; mytag`roses are not ${b + ‘e’}, violets are not ${r}`; // ”anything you want”
  • 23. destructuring let [a, b, c] = [-1, -2, -3]; console.log(‘a =’, a, ‘b =’, b, ‘d !=’, c); // a = -1 b = -2 d != -3 let [ , , d] = [4, 5, -6]; console.log(‘d =’, d); // d = -6 let [e, [f, [g]]] = [7, [8, [9]]]; let [first, ...rest] = [‘first’, ‘r’, ‘e’, ‘s’, ‘t’]; console.log(‘first =‘, first, ‘rest =’, rest); // first = ‘first’ rest = [‘r’, ‘e’, ‘s’, ‘t’]
  • 24. let {name: theName, age} = {name: ‘4real Superman Wheaton’, age: 31}; console.log(‘name =’, theName); // name = “4real Superman Wheaton” console.log(‘age =’, age); // age = 31 let nested = {very: [‘little’, {baby: ‘bird’}] }, {very: [little, {baby}] } = nested; console.log(‘little =’, little, ‘baby =’, bird); // little = “little” baby = “bird” let [a = 1, b = 2] = [3]; // a = 3, b = 2 let {w: y = ‘z’} = {v: ‘v’}; // y = ‘z’ destructuring
  • 25. function http({url, method, data}) { fetch(url, {method, body: data}).then(response => alert(response)); } http({url: ‘http://com.net’, method: ‘post’, data: {id: ‘di’, name: ‘ne im’}}); destructuring
  • 26. - syntactic sugar over prototypal inheritance - fundamentally they are functions and just as functions they can have both forms (as declarations and as expressions) class class declaration class Point { constructor(x, y) { this.x = x; this.y = y; } } class expression let Point = class { constructor(x, y) { this.x = x; this.y = y; } }
  • 27. class Point { constructor(x, y) { this.x = x; this.y = y; } static distance(p, q) { return Math.sqrt((p.x - q.x) ** 2 + (p.y - q.y) ** 2 ); } } console.log(new Point(1, 1), new Point(5, 4)); // 5 class - static keyword
  • 28. class ColorPoint extends Point { constructor(x, y, color) { super(x, y); this.color = color; } } let cp = new ColorPoint(1, 1, ‘green’)); class - extends and super keywords
  • 29. - generators are functions which can be exited and later re-entered - their context (variable bindings) will be saved across re-entrances - returns an iterator function* idMaker() { let index = 0; while(index < 3) yield index++; } let gen = idMaker(); console.log(gen.next()); // {value: 0, done: false} console.log(gen.next()); // {value: 1, done: false} console.log(gen.next()); // {value: 2, done: false} console.log(gen.next()); // {value: undefined, done: true} generators
  • 30. - yield* delegates to another generator function function* generator(i) { yield i; yield* idMaker(i); yield i + 10; } let gen = generator(10); console.log(gen.next()); // {value: 10, done: false} console.log(gen.next()); // {value: 0, done: false} console.log(gen.next()); // {value: 1, done: false} console.log(gen.next()); // {value: 2, done: false} console.log(gen.next()); // {value: 20, done: false} console.log(gen.next()); // {value: undefined, done: true} generators
  • 31. Differences between objects and maps: ● An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done. ● The keys of an Object are Strings and Symbols, where they can be any value for a Map. ● You can get the size of a Map easily while you have to manually keep track of size for an Object. Map - new Map([iterable])
  • 32. - the Set object lets you store unique values of any type, whether primitive values or object references. - you can iterate its elements in insertion order Set - new Set([iterable]);
  • 33. - asynchronous code written in a synchronous manner - syntactic sugar over generators function getAPromise() { return new Promise(resolve => setTimeout(() => resolve(‘hello!’), 3000)); } async function doStuff() { let value = await getAPromise(); console.log(‘value of the promise is’, value); } doStuff(); // value of the promise is hello! async/await - ES7 (stage 3)
  • 34. function getData(url) { return fetch(url); } (async function() { let urls = [‘users/1’, ‘users/2’, ‘users/3’]; for(let data of urls.map(getData)) { // makes requests in parallel console.log((await data).name); // logs the user names in order } }()); async/await - ES7 (stage 3)
  • 35. - asynchronously observing the changes to an object - it provides a stream of changes in the order in which they occur let obj = {foo: 0, bar: 1}; Object.observe(obj, function(changes) { console.log(changes); }); obj.baz = 2; // [{name: 'baz', object: <obj>, type: 'add'}] obj.foo = 'hello'; // [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}] delete obj.baz; // [{name: 'baz', object: <obj>, type: 'delete', oldValue: 2}] Object.defineProperty(obj, 'foo', {writable: false}); // [{name: 'foo', object: <obj>, type: 'reconfigure'}] Object.observe - ES7 (stage 2)
  • 36. - proposal for an Observable type - used to model push-based data sources such as DOM events, timer intervals, sockets and others - can be composed with higher-order combinators - they do not start emitting data until an observer has subscribed Observables - ES7 (stage 1)
  • 37. function listen(element, eventName) { return new Observable(observer => { // Create an event handler which sends data to the observer let handler = event => observer.next(event); // Attach the event handler element.addEventListener(eventName, handler, true); }); } Observables - ES7 (stage 1)
  • 38. // Return an observable of special key down commands function commandKeys(element) { let keyCommands = { "38": "up", "40": "down" }; return listen(element, "keydown") .filter(event => event.keyCode in keyCommands) .map(event => keyCommands[event.keyCode]) } commandKeys(inputElement).subscribe({ next(val) { console.log("Received key command: " + val) }, // “up” “down” “up” “up” “down” “up” // error(err) { console.log("Received an error: " + err) }, // complete() { console.log("Stream complete") } }); Observables - ES7 (stage 1)
  • 39. A decorator is: - an expression - that evaluates to a function - that takes the target, name, and property descriptor as arguments - and optionally returns a property descriptor to install on the target object class Person { @nonenumerable get kidCount() { return this.children.length; } } function nonenumerable(target, name, descriptor) { descriptor.enumerable = false; return descriptor; } class and property decorators - ES7 (stage 1)
  • 40. - It is also possible to decorate the class itself. In this case, the decorator takes the target constructor. @annotation class MyClass { } function annotation(target) { // Add a property on target target.annotated = true; } class and property decorators - ES7 (stage 1)
  • 41. - since decorators are expressions, decorators can take additional arguments and act like a factory class C { @enumerable(false) method() { } } function enumerable(value) { return function (target, key, descriptor) { descriptor.enumerable = value; return descriptor; } } class and property decorators - ES7 (stage 1)