SlideShare a Scribd company logo
JAVASCRIPT
& TYPESCRIPT
Roberto Cappelletti & Vittorio Sozzi
23/04/2015Javascript
2
Indice
• Tipi di dato
• Uguaglianze
• Funzioni
• Scope
• Oggetti
• Prototype
• Ereditarietà
• Modulo
• AMD
• Introduzione Typescript
Obiettivi
• Logica applicativa si sposta dal server al client
• Linguaggio cross-OS, cross-device, ….
– SPA
– Office App
• Non solo nel browser
– MongoDB
– Win.JS
– Node.js (framework lato server)
• Javascript è sempre più importante e onnipresente
• “JavaScript is the only language people feel like they don't need
to learn to use it” (Douglas Crockford)
23/04/2015Javascript
3
Tipi di dato
23/04/2015Javascript
4
var string = 'mia stringa'; stringa
var number = 1.2;
var boolean = true;
numerico
booleano
var obj = {};
var a = [];
oggetto
array
a[0] = 'Hello';
a[1] = 'world';
a[2] = 7;
a.Length; // 3
a[1000] = true;
a.Length = 1001
Comparazione
23/04/2015Javascript
5
var s = 'string';
var s2 = 'another string';
s == s2 ? // false
var s = 'string';
var n = 1
s == n ? // false
var s = '1';
var n = 1
s == n ? // true!
== !=
s == b ? // true!
var s = 'true';
var b = true;
s == b ? // false!
var s = '1';
var b = true;
=== !==
Funzioni
23/04/2015Javascript
6
// function definition (global)
function greet(name) {
return 'hello ' + name;
}
// anonymous function expression
var greet = function (name) {
return 'hello ' + name;
}
// passed as argument
var surround = function (func, name) {
return '(' + func(name)) + ‘)';
}
// returned
var makeGreet = function () {
return function(name) {
return ‘hello ' + name;
};
}
Scope
23/04/2015Javascript
7
var foo = function () {
var a = 3;
var b = 5;
var bar = function () {
var b = 7;
var c = 11;
a += b + c;
// a = 21, b:7, c:11
};
// a = 3, b = 5
bar();
// a = 21, b = 5
};
• Non a blocchi
• Scope lessicale
• Scope chain
Hoisting
23/04/2015Javascript
8
var myvar = 'my value';
var f = function () {
console.log(myvar);
var myvar = 'wohooo';
console.log(myvar);
};
var myvar = 'my value';
var f = function () {
console.log(myvar);
};
var myvar = 'my value';
var f = function () {
var myvar;
console.log(myvar);
myvar = 'wohooo';
console.log(myvar);
};
// my value// undefined
// 'wohooo'
• La dichiarazione viene spostata
all’inzio dello scope
• Stessa cosa per la dichiarazione
di funzioni
Closure (chiusura)
• Le funzioni interne hanno
accesso alle variabili e ai
parametri delle funzioni
«padre»
• Variabili, non valori
23/04/2015Javascript
9
var myFunc = function (args) {
var bar = 'baz';
return {
getBar: function () {
return bar + args;
}
}
};
console.log(myFunc('!').getBar());
var createCounter = function () {
var startValue = 1;
return function () {
return startValue++;
};
};
var counter = createCounter();
console.log(counter());
console.log(counter());
console.log(counter());
// 1
// 2
// 3
// baz!
Oggetti
• Gli array sono oggetti
• Le funzioni sono oggetti
• Gli oggetti… sono oggetti
• Ma cosa sono gli oggetti?
– Gli oggetti sono
collection
di coppie chiave-valore
(proprietà)
23/04/2015Javascript
10
var foo = {}; // vuoto
var obj = {
name: {
first: 'Vittorio',
surname: 'Sozzi'
},
age: 29,
active: true,
twitter: function () {
var n = this.name;
return '@'
+ n.first.substr(0, 5)
+ n.surname.substr(0, 2);
},
tags: ['web', 'js', '.net', 'c#']
};
Oggetti
23/04/2015Javascript
11
var person = {};
// set operations
person.name = 'roberto';
person['surname'] = 'cappelletti';
// get operations
var n = person.name;
var s = person['surname']:
var a = person.age || ‘not set’; // safe
// delete operations
delete person.surname;
// enumeration
var prop;
for (prop in person) {
console.log(prop + ‘:’ + person[prop]);
} // name:roberto
// methods
person.say = function (word) {
return word + ‘ ‘ + this.name;
}
console.log(person.say(‘hello’));
// hello roberto
Prototype
• Permette ad un oggetto di
ereditare le proprietà di un altro
oggetto
23/04/2015Javascript
12
var name = {
first: ‘marco’,
last: ‘rossi’
};
var twitter = Object.create(name);
twitter.account = function() {
return ‘@’ + this.first + this.last;
}
console.log(twitter.account());
// @marcorossi
twitter
account: ...
prototype: -
name
first: ...
last: ...
prototype: -
Object
prototype: -
This
• Diverso dal C#
• ‘This’ rappresenta il contesto
• Determinato dall’invocazione
– Function invocation
– Method invocation
– Constructor invocation
– Apply invocation
23/04/2015Javascript
13
This (esempi)
23/04/2015Javascript
14
// function invocation
var sum = function (a,b) {
console.log(this);
return a + b;
};
// bound to global object
var value = sum (1,2);
// method invocation
var foo = {
value: 0,
increment: function (inc) {
this.value += inc;
}
};
// bound to foo
foo.increment(2);
// constructor invocation
var foo = function (string) {
this.bar = string;
};
// bound to the new object
var one = new Foo(‘one’);
var two = new Foo(‘two’);
// apply invocation
var foo = {
value: 0
};
var increment = function (inc) {
this.value += inc;
};
// bound to the first param
increment.apply(foo, [1]);
Creare oggetti
• Javascript fornisce più
modi di creare un oggetto
• Object Literal
– Vogliamo un solo
oggetto
– Ridurre un numero
elevato di parametri
– Raccogliere
configurazioni
• Maker function
23/04/2015Javascript
15
var makePerson = function () {
var settings = {
say: ‘hello’,
name: ‘sir’
};
var greeting = function (spec) {
return spec.say || settings.say
+ ‘ ‘
+ spec.name || settings.name;
};
return {
greeting: greeting
}
};
var p = makePerson();
var result = p.greeting({ name: ‘roberto’});
// result: hello roberto
Creare oggetti
• Javascript fornisce più modi
di creare un oggetto
• Constructor Function
– Quando vogliamo più
istanze indipendenti
di un oggetto
– Logica del
costruttore
– Riduce l’allocazione di
memoria
23/04/2015Javascript
16
var Person = function (name) {
this.name = name;
// bad: redefined for each new objects
this.toString = function () {
return ‘I am ‘ + this.name;
};
};
// good: defined one time for all objects
Person.prototype.greeting = function (say) {
return say + ‘ ‘ + this.name;
};
var p1 = new Person(‘roberto’);
var p2 = new Person(‘tizio’);
var result1 = p1.greeting(‘hi’);
var result2 = p2.toString();
// result1: hi roberto
// result2: I am tizio
Creare oggetti
• Javascript fornisce più modi
di creare un oggetto
• ECMAScript 5
– Creare un oggetto senza
utilizzare il suo
costruttore
23/04/2015Javascript
17
var Person = Object.create(Object.prototype);
Person.prototype = {
greeting: function (say) {
return say + ‘‘ + this.name;
}
};
var p = Object.create(Person.prototype, {
name: {
writable: true,
configurable: true,
value: ‘roberto’
}
});
var result = p.greeting(‘hi’);
// result: hi roberto
Information Hiding
• Non si possono marcare le
variabili come private
• Possiamo usare funzioni e
closure…
23/04/2015Javascript
18
// all public members
var foo = {
names: [‘one’, ‘two’, ‘three’],
digit_name: function (n) {
return this.names[n];
}
};
// remove ‘three’ means changing
// internal state, very very very bad!!!
foo.names.splice(2,1);
console.log(foo.digit_name(2));
// undefined
// private
var digit_name = function (n) {
var names = [‘one’, ‘two’, ‘three’];
return this.names[n];
};
var foo = {
digit_name: digit_name
};
console.log(foo.digit_name(2));
// three
Ereditarietà
• Tante possibili tecniche
• Modo naturale JavaScript
• Senza il concetto di classe
• Gli oggetti ereditano da
oggetti (Delegation)
• Personalizzo il nuovo oggetto
(Differential Inheritance)
• Standard del linguaggio
(ECMAScript 5)
23/04/2015Javascript
19
var car = {
speed: 0,
accelerates: function (level) {
this.speed += level;
}
};
// supercar inherits from car
var supercar = Object.create(car);
supercar.boost = function() {
this.accelerates(100);
};
car.accelerates(2);
supercar.boost();
console.log(car.speed);
console.log(supercar.speed);
console.log(supercar.hasOwnProperty('accelerates'));
// 2 102 false
Iteratori
• Prendono una funzione di
callback come parametro
• Applica il callback ad ogni
elemento
• Sintassi compatta, nasconde
tutta la logica di
attraversamento
23/04/2015Javascript
20
var numbers = [1, 4, 9];
numbers.forEach(function (x) {
console.log(x);
});
numbers.every(function (x) {
return x % 2 === 0;
}); // false
numbers.some(function (x) {
return x % 2 === 0;
}); // true
numbers.map(function (x) {
return x % x;
}); // [1, 16, 81]
numbers.filter(function (x) {
return x % 2 === 0;
}); // 4
numbers.reduce (function (x, y) {
return x + y;
}); // 14
mmmmm…
callback…
Pattern Module
• I Moduli rappresentano un
parte unica, fornisce un
modo di raggruppare metodi
e variabili
• Impedisce l’inquinamento
del global scope
• Soluzione pulita per
nascondere la logica
dall’esterno del modulo
23/04/2015Javascript
21
var Person = (function () {
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return "Hello, " + this.name;
};
return Person;
})();
Asynchronous Module Definition Pattern
(AMD)
• Un modo per scrivere
codice Javascript modulare
• Separazione fra la
definizione del modulo
(define) e il caricamento
delle dipendenze (require)
• Possono essere caricate in
maniera asincrona
23/04/2015Javascript
22
Typescript
• TypeScript is a syntactic sugar for JavaScript
• TypeScript è Javascript ECMAScript 5 con
l’aggiunta di alcuni costrutti ECMAScript 6.
• Alcune caratteristiche:
– Tipizzazione statica
– Classi
– Interfacce
– Moduli
23/04/2015Typescript
23
23/04/2015Titolo Meeting
24
Grazie a tutti
“The World's Most Misunderstood
Programming Language”
Douglas Crockford

More Related Content

What's hot

jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesigner
Matteo Magni
 
Ruby in 25 minuti
Ruby in 25 minutiRuby in 25 minuti
Ruby in 25 minuti
Marcello Missiroli
 
Node.js - Server Side Javascript
Node.js - Server Side JavascriptNode.js - Server Side Javascript
Node.js - Server Side Javascript
Matteo Napolitano
 
Ajax Primi Passi Per Iniziare
Ajax Primi Passi Per IniziareAjax Primi Passi Per Iniziare
Ajax Primi Passi Per Iniziareastanco
 
Ajax Primi Passi Per Iniziare
Ajax Primi Passi Per IniziareAjax Primi Passi Per Iniziare
Ajax Primi Passi Per Iniziare
astanco
 
Php mysql3
Php mysql3Php mysql3
Php mysql3
orestJump
 
Closure Visto Da Vicino
Closure Visto Da VicinoClosure Visto Da Vicino
Closure Visto Da Vicino
davide ficano
 
Applicazioni native in java
Applicazioni native in javaApplicazioni native in java
Applicazioni native in java
Federico Paparoni
 
Javascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerJavascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesigner
Matteo Magni
 
jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesigner
Matteo Magni
 
Drupal Day 2011 - Node.js e Drupal
Drupal Day 2011 - Node.js e DrupalDrupal Day 2011 - Node.js e Drupal
Drupal Day 2011 - Node.js e Drupal
DrupalDay
 
Design Pattern
Design PatternDesign Pattern
Design Pattern
Giuseppe Dell'Abate
 
Lezione 9: Web Service in Java
Lezione 9: Web Service in JavaLezione 9: Web Service in Java
Lezione 9: Web Service in Java
Andrea Della Corte
 
Sviluppo web dall'antichità all'avanguardia e ritorno
Sviluppo web  dall'antichità all'avanguardia e ritornoSviluppo web  dall'antichità all'avanguardia e ritorno
Sviluppo web dall'antichità all'avanguardia e ritorno
lordarthas
 
corso web developer - Introduzione a Javascript
corso web developer - Introduzione a Javascriptcorso web developer - Introduzione a Javascript
corso web developer - Introduzione a Javascript
Riccardo Piccioni
 
Vb.Net
Vb.NetVb.Net
PHP Object Injection
PHP Object InjectionPHP Object Injection
PHP Object Injection
Minded Security
 
Lezione 7: Remote Method Invocation e SSL
Lezione 7: Remote Method Invocation e SSLLezione 7: Remote Method Invocation e SSL
Lezione 7: Remote Method Invocation e SSL
Andrea Della Corte
 
Lezione 6: Remote Method Invocation
Lezione 6: Remote Method InvocationLezione 6: Remote Method Invocation
Lezione 6: Remote Method Invocation
Andrea Della Corte
 
Lezione 10: Web Service in Java (2)
Lezione 10: Web Service in Java (2)Lezione 10: Web Service in Java (2)
Lezione 10: Web Service in Java (2)
Andrea Della Corte
 

What's hot (20)

jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesigner
 
Ruby in 25 minuti
Ruby in 25 minutiRuby in 25 minuti
Ruby in 25 minuti
 
Node.js - Server Side Javascript
Node.js - Server Side JavascriptNode.js - Server Side Javascript
Node.js - Server Side Javascript
 
Ajax Primi Passi Per Iniziare
Ajax Primi Passi Per IniziareAjax Primi Passi Per Iniziare
Ajax Primi Passi Per Iniziare
 
Ajax Primi Passi Per Iniziare
Ajax Primi Passi Per IniziareAjax Primi Passi Per Iniziare
Ajax Primi Passi Per Iniziare
 
Php mysql3
Php mysql3Php mysql3
Php mysql3
 
Closure Visto Da Vicino
Closure Visto Da VicinoClosure Visto Da Vicino
Closure Visto Da Vicino
 
Applicazioni native in java
Applicazioni native in javaApplicazioni native in java
Applicazioni native in java
 
Javascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerJavascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesigner
 
jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesigner
 
Drupal Day 2011 - Node.js e Drupal
Drupal Day 2011 - Node.js e DrupalDrupal Day 2011 - Node.js e Drupal
Drupal Day 2011 - Node.js e Drupal
 
Design Pattern
Design PatternDesign Pattern
Design Pattern
 
Lezione 9: Web Service in Java
Lezione 9: Web Service in JavaLezione 9: Web Service in Java
Lezione 9: Web Service in Java
 
Sviluppo web dall'antichità all'avanguardia e ritorno
Sviluppo web  dall'antichità all'avanguardia e ritornoSviluppo web  dall'antichità all'avanguardia e ritorno
Sviluppo web dall'antichità all'avanguardia e ritorno
 
corso web developer - Introduzione a Javascript
corso web developer - Introduzione a Javascriptcorso web developer - Introduzione a Javascript
corso web developer - Introduzione a Javascript
 
Vb.Net
Vb.NetVb.Net
Vb.Net
 
PHP Object Injection
PHP Object InjectionPHP Object Injection
PHP Object Injection
 
Lezione 7: Remote Method Invocation e SSL
Lezione 7: Remote Method Invocation e SSLLezione 7: Remote Method Invocation e SSL
Lezione 7: Remote Method Invocation e SSL
 
Lezione 6: Remote Method Invocation
Lezione 6: Remote Method InvocationLezione 6: Remote Method Invocation
Lezione 6: Remote Method Invocation
 
Lezione 10: Web Service in Java (2)
Lezione 10: Web Service in Java (2)Lezione 10: Web Service in Java (2)
Lezione 10: Web Service in Java (2)
 

Similar to Javascript

Mobile APPs con Objective-C (iOS 3.1+) - Day 01/02
Mobile APPs con Objective-C (iOS 3.1+) - Day 01/02Mobile APPs con Objective-C (iOS 3.1+) - Day 01/02
Mobile APPs con Objective-C (iOS 3.1+) - Day 01/02
Alberto Pasca
 
AngularJS: server communication
AngularJS: server communicationAngularJS: server communication
AngularJS: server communicationVittorio Conte
 
E suap - tecnologie client
E suap - tecnologie client E suap - tecnologie client
E suap - tecnologie client
Sabino Labarile
 
Programmazione web libera dai framework
Programmazione web libera dai frameworkProgrammazione web libera dai framework
Programmazione web libera dai framework
Francesca1980
 
Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacyTommaso Torti
 
Hexagonal architecture ita
Hexagonal architecture itaHexagonal architecture ita
Hexagonal architecture ita
Alessandro Minoccheri
 
Rich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in JqueryRich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in JqueryAlberto Buschettu
 
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case studyMantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
DrupalDay
 
Yagwto
YagwtoYagwto
Write less do more...with jQuery
Write less do more...with jQueryWrite less do more...with jQuery
Write less do more...with jQuery
XeDotNet
 
Introduzione a node.js
Introduzione a node.jsIntroduzione a node.js
Introduzione a node.js
Luciano Colosio
 
Introduzione a Node.js
Introduzione a Node.jsIntroduzione a Node.js
Introduzione a Node.js
Michele Capra
 
Oo Javascript
Oo JavascriptOo Javascript
Oo Javascript
maraexception
 
Asp.net gestione della_memoria
Asp.net gestione della_memoriaAsp.net gestione della_memoria
Asp.net gestione della_memoriaCrismer La Pignola
 
Non Conventional Android Programming (Italiano)
Non Conventional Android Programming (Italiano)Non Conventional Android Programming (Italiano)
Non Conventional Android Programming (Italiano)
Davide Cerbo
 
Perl Template Toolkit
Perl Template ToolkitPerl Template Toolkit
Perl Template Toolkit
Stefano Rodighiero
 
DotNetToscana - Sessione TypeScript
DotNetToscana - Sessione TypeScriptDotNetToscana - Sessione TypeScript
DotNetToscana - Sessione TypeScriptSinergia Totale
 
Go reactive with Realm and Xamarin Forms - Andrea Ceroni - Codemotion Rome 2018
Go reactive with Realm and Xamarin Forms - Andrea Ceroni - Codemotion Rome 2018Go reactive with Realm and Xamarin Forms - Andrea Ceroni - Codemotion Rome 2018
Go reactive with Realm and Xamarin Forms - Andrea Ceroni - Codemotion Rome 2018
Codemotion
 
Sviluppo web con Ruby on Rails
Sviluppo web con Ruby on RailsSviluppo web con Ruby on Rails
Sviluppo web con Ruby on Rails
jekil
 

Similar to Javascript (20)

Mobile APPs con Objective-C (iOS 3.1+) - Day 01/02
Mobile APPs con Objective-C (iOS 3.1+) - Day 01/02Mobile APPs con Objective-C (iOS 3.1+) - Day 01/02
Mobile APPs con Objective-C (iOS 3.1+) - Day 01/02
 
AngularJS: server communication
AngularJS: server communicationAngularJS: server communication
AngularJS: server communication
 
E suap - tecnologie client
E suap - tecnologie client E suap - tecnologie client
E suap - tecnologie client
 
Programmazione web libera dai framework
Programmazione web libera dai frameworkProgrammazione web libera dai framework
Programmazione web libera dai framework
 
Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacy
 
Hexagonal architecture ita
Hexagonal architecture itaHexagonal architecture ita
Hexagonal architecture ita
 
Pillole di C++
Pillole di C++Pillole di C++
Pillole di C++
 
Rich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in JqueryRich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in Jquery
 
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case studyMantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
 
Yagwto
YagwtoYagwto
Yagwto
 
Write less do more...with jQuery
Write less do more...with jQueryWrite less do more...with jQuery
Write less do more...with jQuery
 
Introduzione a node.js
Introduzione a node.jsIntroduzione a node.js
Introduzione a node.js
 
Introduzione a Node.js
Introduzione a Node.jsIntroduzione a Node.js
Introduzione a Node.js
 
Oo Javascript
Oo JavascriptOo Javascript
Oo Javascript
 
Asp.net gestione della_memoria
Asp.net gestione della_memoriaAsp.net gestione della_memoria
Asp.net gestione della_memoria
 
Non Conventional Android Programming (Italiano)
Non Conventional Android Programming (Italiano)Non Conventional Android Programming (Italiano)
Non Conventional Android Programming (Italiano)
 
Perl Template Toolkit
Perl Template ToolkitPerl Template Toolkit
Perl Template Toolkit
 
DotNetToscana - Sessione TypeScript
DotNetToscana - Sessione TypeScriptDotNetToscana - Sessione TypeScript
DotNetToscana - Sessione TypeScript
 
Go reactive with Realm and Xamarin Forms - Andrea Ceroni - Codemotion Rome 2018
Go reactive with Realm and Xamarin Forms - Andrea Ceroni - Codemotion Rome 2018Go reactive with Realm and Xamarin Forms - Andrea Ceroni - Codemotion Rome 2018
Go reactive with Realm and Xamarin Forms - Andrea Ceroni - Codemotion Rome 2018
 
Sviluppo web con Ruby on Rails
Sviluppo web con Ruby on RailsSviluppo web con Ruby on Rails
Sviluppo web con Ruby on Rails
 

Javascript

  • 2. 23/04/2015Javascript 2 Indice • Tipi di dato • Uguaglianze • Funzioni • Scope • Oggetti • Prototype • Ereditarietà • Modulo • AMD • Introduzione Typescript
  • 3. Obiettivi • Logica applicativa si sposta dal server al client • Linguaggio cross-OS, cross-device, …. – SPA – Office App • Non solo nel browser – MongoDB – Win.JS – Node.js (framework lato server) • Javascript è sempre più importante e onnipresente • “JavaScript is the only language people feel like they don't need to learn to use it” (Douglas Crockford) 23/04/2015Javascript 3
  • 4. Tipi di dato 23/04/2015Javascript 4 var string = 'mia stringa'; stringa var number = 1.2; var boolean = true; numerico booleano var obj = {}; var a = []; oggetto array a[0] = 'Hello'; a[1] = 'world'; a[2] = 7; a.Length; // 3 a[1000] = true; a.Length = 1001
  • 5. Comparazione 23/04/2015Javascript 5 var s = 'string'; var s2 = 'another string'; s == s2 ? // false var s = 'string'; var n = 1 s == n ? // false var s = '1'; var n = 1 s == n ? // true! == != s == b ? // true! var s = 'true'; var b = true; s == b ? // false! var s = '1'; var b = true; === !==
  • 6. Funzioni 23/04/2015Javascript 6 // function definition (global) function greet(name) { return 'hello ' + name; } // anonymous function expression var greet = function (name) { return 'hello ' + name; } // passed as argument var surround = function (func, name) { return '(' + func(name)) + ‘)'; } // returned var makeGreet = function () { return function(name) { return ‘hello ' + name; }; }
  • 7. Scope 23/04/2015Javascript 7 var foo = function () { var a = 3; var b = 5; var bar = function () { var b = 7; var c = 11; a += b + c; // a = 21, b:7, c:11 }; // a = 3, b = 5 bar(); // a = 21, b = 5 }; • Non a blocchi • Scope lessicale • Scope chain
  • 8. Hoisting 23/04/2015Javascript 8 var myvar = 'my value'; var f = function () { console.log(myvar); var myvar = 'wohooo'; console.log(myvar); }; var myvar = 'my value'; var f = function () { console.log(myvar); }; var myvar = 'my value'; var f = function () { var myvar; console.log(myvar); myvar = 'wohooo'; console.log(myvar); }; // my value// undefined // 'wohooo' • La dichiarazione viene spostata all’inzio dello scope • Stessa cosa per la dichiarazione di funzioni
  • 9. Closure (chiusura) • Le funzioni interne hanno accesso alle variabili e ai parametri delle funzioni «padre» • Variabili, non valori 23/04/2015Javascript 9 var myFunc = function (args) { var bar = 'baz'; return { getBar: function () { return bar + args; } } }; console.log(myFunc('!').getBar()); var createCounter = function () { var startValue = 1; return function () { return startValue++; }; }; var counter = createCounter(); console.log(counter()); console.log(counter()); console.log(counter()); // 1 // 2 // 3 // baz!
  • 10. Oggetti • Gli array sono oggetti • Le funzioni sono oggetti • Gli oggetti… sono oggetti • Ma cosa sono gli oggetti? – Gli oggetti sono collection di coppie chiave-valore (proprietà) 23/04/2015Javascript 10 var foo = {}; // vuoto var obj = { name: { first: 'Vittorio', surname: 'Sozzi' }, age: 29, active: true, twitter: function () { var n = this.name; return '@' + n.first.substr(0, 5) + n.surname.substr(0, 2); }, tags: ['web', 'js', '.net', 'c#'] };
  • 11. Oggetti 23/04/2015Javascript 11 var person = {}; // set operations person.name = 'roberto'; person['surname'] = 'cappelletti'; // get operations var n = person.name; var s = person['surname']: var a = person.age || ‘not set’; // safe // delete operations delete person.surname; // enumeration var prop; for (prop in person) { console.log(prop + ‘:’ + person[prop]); } // name:roberto // methods person.say = function (word) { return word + ‘ ‘ + this.name; } console.log(person.say(‘hello’)); // hello roberto
  • 12. Prototype • Permette ad un oggetto di ereditare le proprietà di un altro oggetto 23/04/2015Javascript 12 var name = { first: ‘marco’, last: ‘rossi’ }; var twitter = Object.create(name); twitter.account = function() { return ‘@’ + this.first + this.last; } console.log(twitter.account()); // @marcorossi twitter account: ... prototype: - name first: ... last: ... prototype: - Object prototype: -
  • 13. This • Diverso dal C# • ‘This’ rappresenta il contesto • Determinato dall’invocazione – Function invocation – Method invocation – Constructor invocation – Apply invocation 23/04/2015Javascript 13
  • 14. This (esempi) 23/04/2015Javascript 14 // function invocation var sum = function (a,b) { console.log(this); return a + b; }; // bound to global object var value = sum (1,2); // method invocation var foo = { value: 0, increment: function (inc) { this.value += inc; } }; // bound to foo foo.increment(2); // constructor invocation var foo = function (string) { this.bar = string; }; // bound to the new object var one = new Foo(‘one’); var two = new Foo(‘two’); // apply invocation var foo = { value: 0 }; var increment = function (inc) { this.value += inc; }; // bound to the first param increment.apply(foo, [1]);
  • 15. Creare oggetti • Javascript fornisce più modi di creare un oggetto • Object Literal – Vogliamo un solo oggetto – Ridurre un numero elevato di parametri – Raccogliere configurazioni • Maker function 23/04/2015Javascript 15 var makePerson = function () { var settings = { say: ‘hello’, name: ‘sir’ }; var greeting = function (spec) { return spec.say || settings.say + ‘ ‘ + spec.name || settings.name; }; return { greeting: greeting } }; var p = makePerson(); var result = p.greeting({ name: ‘roberto’}); // result: hello roberto
  • 16. Creare oggetti • Javascript fornisce più modi di creare un oggetto • Constructor Function – Quando vogliamo più istanze indipendenti di un oggetto – Logica del costruttore – Riduce l’allocazione di memoria 23/04/2015Javascript 16 var Person = function (name) { this.name = name; // bad: redefined for each new objects this.toString = function () { return ‘I am ‘ + this.name; }; }; // good: defined one time for all objects Person.prototype.greeting = function (say) { return say + ‘ ‘ + this.name; }; var p1 = new Person(‘roberto’); var p2 = new Person(‘tizio’); var result1 = p1.greeting(‘hi’); var result2 = p2.toString(); // result1: hi roberto // result2: I am tizio
  • 17. Creare oggetti • Javascript fornisce più modi di creare un oggetto • ECMAScript 5 – Creare un oggetto senza utilizzare il suo costruttore 23/04/2015Javascript 17 var Person = Object.create(Object.prototype); Person.prototype = { greeting: function (say) { return say + ‘‘ + this.name; } }; var p = Object.create(Person.prototype, { name: { writable: true, configurable: true, value: ‘roberto’ } }); var result = p.greeting(‘hi’); // result: hi roberto
  • 18. Information Hiding • Non si possono marcare le variabili come private • Possiamo usare funzioni e closure… 23/04/2015Javascript 18 // all public members var foo = { names: [‘one’, ‘two’, ‘three’], digit_name: function (n) { return this.names[n]; } }; // remove ‘three’ means changing // internal state, very very very bad!!! foo.names.splice(2,1); console.log(foo.digit_name(2)); // undefined // private var digit_name = function (n) { var names = [‘one’, ‘two’, ‘three’]; return this.names[n]; }; var foo = { digit_name: digit_name }; console.log(foo.digit_name(2)); // three
  • 19. Ereditarietà • Tante possibili tecniche • Modo naturale JavaScript • Senza il concetto di classe • Gli oggetti ereditano da oggetti (Delegation) • Personalizzo il nuovo oggetto (Differential Inheritance) • Standard del linguaggio (ECMAScript 5) 23/04/2015Javascript 19 var car = { speed: 0, accelerates: function (level) { this.speed += level; } }; // supercar inherits from car var supercar = Object.create(car); supercar.boost = function() { this.accelerates(100); }; car.accelerates(2); supercar.boost(); console.log(car.speed); console.log(supercar.speed); console.log(supercar.hasOwnProperty('accelerates')); // 2 102 false
  • 20. Iteratori • Prendono una funzione di callback come parametro • Applica il callback ad ogni elemento • Sintassi compatta, nasconde tutta la logica di attraversamento 23/04/2015Javascript 20 var numbers = [1, 4, 9]; numbers.forEach(function (x) { console.log(x); }); numbers.every(function (x) { return x % 2 === 0; }); // false numbers.some(function (x) { return x % 2 === 0; }); // true numbers.map(function (x) { return x % x; }); // [1, 16, 81] numbers.filter(function (x) { return x % 2 === 0; }); // 4 numbers.reduce (function (x, y) { return x + y; }); // 14 mmmmm… callback…
  • 21. Pattern Module • I Moduli rappresentano un parte unica, fornisce un modo di raggruppare metodi e variabili • Impedisce l’inquinamento del global scope • Soluzione pulita per nascondere la logica dall’esterno del modulo 23/04/2015Javascript 21 var Person = (function () { function Person(name) { this.name = name; } Person.prototype.greet = function () { return "Hello, " + this.name; }; return Person; })();
  • 22. Asynchronous Module Definition Pattern (AMD) • Un modo per scrivere codice Javascript modulare • Separazione fra la definizione del modulo (define) e il caricamento delle dipendenze (require) • Possono essere caricate in maniera asincrona 23/04/2015Javascript 22
  • 23. Typescript • TypeScript is a syntactic sugar for JavaScript • TypeScript è Javascript ECMAScript 5 con l’aggiunta di alcuni costrutti ECMAScript 6. • Alcune caratteristiche: – Tipizzazione statica – Classi – Interfacce – Moduli 23/04/2015Typescript 23
  • 24. 23/04/2015Titolo Meeting 24 Grazie a tutti “The World's Most Misunderstood Programming Language” Douglas Crockford

Editor's Notes

  1. Sono oggetti a tutti gli effetti