Javascript
-
Upload
roberto-cappelletti -
Category
Internet
-
view
35 -
download
0
Transcript of Javascript
15/04/2023
2
Javascript
Indice
• Tipi di dato• Uguaglianze• Funzioni• Scope• Oggetti• Prototype• Ereditarietà• Modulo• AMD• Introduzione Typescript
15/04/2023Javascript
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)
15/04/2023
4
Tipi di dato
Javascript
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
15/04/2023
5
Comparazione
Javascript
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;
=== !==
15/04/2023
6
Funzioni
Javascript
// function definition (global)function greet(name) { return 'hello ' + name;}
// anonymous function expressionvar greet = function (name) { return 'hello ' + name;}
// passed as argumentvar surround = function (func, name) { return '(' + func(name)) + ‘)';}
// returnedvar makeGreet = function () { return function(name) { return ‘hello ' + name; };}
15/04/2023
7
Scope
Javascript
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
15/04/2023
8
Hoisting
Javascript
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
15/04/2023
9
Closure (chiusura)• Le funzioni interne hanno
accesso alle variabili e ai parametri delle funzioni «padre»
• Variabili, non valori
Javascript
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!
15/04/2023Javascript
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à)
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#']};
15/04/2023Javascript
11
Oggetti
var person = {};
// set operationsperson.name = 'roberto';person['surname'] = 'cappelletti';
// get operationsvar n = person.name;var s = person['surname']:var a = person.age || ‘not set’; // safe
// delete operationsdelete person.surname;
// enumerationvar prop;for (prop in person) { console.log(prop + ‘:’ + person[prop]);} // name:roberto
// methodsperson.say = function (word) { return word + ‘ ‘ + this.name;}
console.log(person.say(‘hello’));// hello roberto
15/04/2023Javascript
12
Prototype• Permette ad un oggetto di
ereditare le proprietà di un altro oggetto
var name = { first: ‘marco’, last: ‘rossi’};
var twitter = Object.create(name);twitter.account = function() { return ‘@’ + this.first + this.last;}
console.log(twitter.account());// @marcorossi
account: ...
prototype: -
name
first: ...
last: ...
prototype: -
Object
prototype: -
15/04/2023Javascript
13
This• Diverso dal C#• ‘This’ rappresenta il contesto• Determinato dall’invocazione
– Function invocation – Method invocation – Constructor invocation – Apply invocation
15/04/2023Javascript
14
This (esempi)
// function invocationvar sum = function (a,b) { console.log(this); return a + b;};// bound to global objectvar value = sum (1,2);
// method invocationvar foo = { value: 0, increment: function (inc) { this.value += inc; }};// bound to foofoo.increment(2);
// constructor invocationvar foo = function (string) { this.bar = string;};// bound to the new objectvar one = new Foo(‘one’);var two = new Foo(‘two’);
// apply invocationvar foo = { value: 0};var increment = function (inc) { this.value += inc;};// bound to the first paramincrement.apply(foo, [1]);
15/04/2023Javascript
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
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
15/04/2023Javascript
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
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 objectsPerson.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
15/04/2023Javascript
17
Creare oggetti• Javascript fornisce più modi
di creare un oggetto
• ECMAScript 5– Creare un oggetto senza
utilizzare il suo costruttore
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
15/04/2023Javascript
18
Information Hiding• Non si possono marcare le
variabili come private• Possiamo usare funzioni e
closure…
// all public membersvar 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
// privatevar 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
15/04/2023Javascript
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)
var car = { speed: 0, accelerates: function (level) { this.speed += level; }};
// supercar inherits from carvar 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
15/04/2023Javascript
20
Iteratori• Prendono una funzione di
callback come parametro• Applica il callback ad ogni
elemento• Sintassi compatta, nasconde
tutta la logica di attraversamento
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…
15/04/2023Javascript
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
var Person = (function () { function Person(name) { this.name = name; } Person.prototype.greet = function () { return "Hello, " + this.name; }; return Person;})();
15/04/2023Javascript
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
15/04/2023
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
Typescript