SlideShare a Scribd company logo
OBJECT  ORIENTED  JAVASCRIPT guida per un mondo migliore Davide Cerbo http://jesty.it Stefano Linguerri http://www.eljeko.net
Una cattiva impressione
L'unione fa la forza JAVASCRIPT + PROTOTYPE
Perché usare Prototype Codice più breve
Sintassi più chiara
Gestisce le incompatibilità trai vari browser
Fornisce diverse funzioni e oggetti di utilità
Permette lo sviluppo di Javascript non intrusivo
E' complementare a Script.aculo.us
Qualcosa di utile $('...')  -> come  getDocumentById('...') ma ritorna un Element di Prototype
$$('...')  ->  Selettore CSS $$('.menu #submenu)   ritorna tutti gli elementi che hanno class submenu all'interno di  un elemento che ha id menu
Ajax.request(Url, {...}) ->  Esegue una richiesta AJAX, le graffe conterranno le opzioni della request:  new Ajax.Request(url, {onSuccess:  function(transport) {...}); Esistono anche altri metodi come: updater e periodicalUpdater.
Template  -> Permette di definire delle stringe parametrizzabili var t = new Template('Name: #{name}, surname: #{surname}'); var show = {name: 'Davide', surname: 'Cerbo'}; t.evaluate(show); //return “Name: Davide, surname: Cerbo”
Observer  -> Permette di osservare gli eventi su un elemento $('id').observe('click', function(element){...});
Di cosa abbiamo bisogno? Per considerare  JAVASCRIPT  un linguaggio  Object Oriented  abbiamo bisogno di:
Strutture dati complesse
Classi
Interfacce
Polimorfismo
Strutture dati complesse Hash  ->  var h = new Hash();  h.set(“key”, “value”); h.get(“key”); //return “value” h.unset(“key”); h.toQueryString() //return “key1=v1&key2=v2&...”
Enumerable  ->  sono liste iterabili con metodi come  each, map, find, select, etc... $A(...).each(function(e){ alert(e.id); }); $$('...') restituisce un Enumerable Sono tutte CLOSURE
Questione di classe Javascript Classico var  Person  = Class.create(); Person.prototype = { initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }; var  jack  = new  Person (“Jack Maffai”); jack.say(“Hi Boy”); //return Jack Maffai: Hi boy! Prototype var  Person  = Class.create({ initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }); var  jack  = new  Person (“Jack Maffai”); jack.say(“Hi Boy”); //return Jack Maffai: Hi boy!
Estendiamo Javascript classico var  Pirate  = Class.create(); Pirate.prototype = Object.extend(new Person(), { say: function(message) { return this.name + ': ' + message + ', yarr!'; } }); Prototype var  Pirate  = Class.create(Person, { say: function($super, message) { return $super(message) + ', yarr!'; } }); new  Pirate (“Jack Maffai”).say(“Hi Boy!”); //say return: Hi Boy!, yarr!
Interfacce? Non ci sono e basta! Accontentiamoci delle classi E ricordiamoci che in Javascript vige la regola: “ If it walks like a duck and quacks like a duck, I would call it a duck.”
Al volo var john = new Pirate('Long John'); john.sleep(); // -> ERROR: sleep is not a method Person.addMethods({ sleep: function() { return this.say('ZzZ'); } }); john.sleep(); // -> "Long John: ZzZ, yarr!" Il metodo viene aggiunto a tutte le istanze e le sottoclassi di Pirate
DOMinare con Prototype Questo approccio deve cambiare il nostro modo di vedere la programmazione Javascript PROGRAMMAZIONE FUNZIONALE
Esempio HTML: <table id=&quot;simonboard&quot;> <TR> <TD id=&quot;red&quot;></TD> <TD id=&quot;blue&quot;></TD> <TD id=&quot;fuchsia&quot;></TD> </TR> <TR> <TD id=&quot;black&quot;></TD> <TD id=&quot;green&quot;></TD> <TD id=&quot;aqua&quot;></TD> </TR> <TR> <TD id=&quot;gold&quot;></TD> <TD id=&quot;magenta&quot;></TD> <TD id=&quot;coral&quot;></TD> </TR> </table> Script di startup: <script language=&quot;JavaScript&quot;> // $('simonboard') -> indica la tabella // 5 -> il numero massimo di quadrati da colorare new Board($('simonboard')).start(5); </script> Il colore predefinito per il quadrato Tabella da utilizzare

More Related Content

ODP
Rich Ajax Web Interfaces in Jquery
ODP
Pycon Jungle
PDF
Introduzione a java script
ODP
ODP
Non Conventional Android Programming (Italiano)
ODP
PPT
Maraton Pisania Listów 2007 - Kogo bronimy
PDF
Social Media in the enterprise
Rich Ajax Web Interfaces in Jquery
Pycon Jungle
Introduzione a java script
Non Conventional Android Programming (Italiano)
Maraton Pisania Listów 2007 - Kogo bronimy
Social Media in the enterprise

Viewers also liked (10)

PDF
Consumer Business Intelligence
PDF
Tapestry 5 in Action Pratica
PPT
NHL Troubleshooting Tool
PPT
Wicket Security Presentation
PPT
Maraton Pisania Listów 2009 - Gimnazjum nr 2 im. Mikołaja Kopernika w Chojnowie
PPT
測試一
PPT
X Maraton Pisania Listów - Bircza
PDF
Tapestry 5 in Action Introduzione
PPT
X Maraton Pisania Listów Amnesty International
PPT
GST 2008 Channel Marketing
Consumer Business Intelligence
Tapestry 5 in Action Pratica
NHL Troubleshooting Tool
Wicket Security Presentation
Maraton Pisania Listów 2009 - Gimnazjum nr 2 im. Mikołaja Kopernika w Chojnowie
測試一
X Maraton Pisania Listów - Bircza
Tapestry 5 in Action Introduzione
X Maraton Pisania Listów Amnesty International
GST 2008 Channel Marketing
Ad

Similar to Oo Javascript (20)

PPTX
PDF
JavaScript Object Oriented
PDF
Introduzione a JavaScript
PPTX
corso web developer - Introduzione a Javascript
PPTX
Diversamente Javascript: si.. può.. fare! (di Mirko Ravaioli)
PDF
Intro to JavaScript
PDF
Javascript - 4 | WebMaster & WebDesigner
PPTX
Javascript avanzato: sfruttare al massimo il web
PDF
15 concetti importanti su javascript
PDF
Cattive abitudini e-lineeguida
PDF
Slide evento Code Refactoring JavaScript
PDF
Corso Javascript
PDF
Javascript - 7 | WebMaster & WebDesigner
PPTX
How create a single page apps using html5 and javascript
PPTX
Lo sai che si può fare DDD in Javascript grazie a Typescript? Visual Studio e...
PDF
Sencha touch: panoramica e orientamento sul codice
PDF
Acadevmy - TypeScript Overview
PDF
EcmaScript 6 & 7
PDF
Le funzioni in javascript
PPT
JavaScript Object Oriented
Introduzione a JavaScript
corso web developer - Introduzione a Javascript
Diversamente Javascript: si.. può.. fare! (di Mirko Ravaioli)
Intro to JavaScript
Javascript - 4 | WebMaster & WebDesigner
Javascript avanzato: sfruttare al massimo il web
15 concetti importanti su javascript
Cattive abitudini e-lineeguida
Slide evento Code Refactoring JavaScript
Corso Javascript
Javascript - 7 | WebMaster & WebDesigner
How create a single page apps using html5 and javascript
Lo sai che si può fare DDD in Javascript grazie a Typescript? Visual Studio e...
Sencha touch: panoramica e orientamento sul codice
Acadevmy - TypeScript Overview
EcmaScript 6 & 7
Le funzioni in javascript
Ad

Oo Javascript

  • 1. OBJECT ORIENTED JAVASCRIPT guida per un mondo migliore Davide Cerbo http://jesty.it Stefano Linguerri http://www.eljeko.net
  • 3. L'unione fa la forza JAVASCRIPT + PROTOTYPE
  • 4. Perché usare Prototype Codice più breve
  • 6. Gestisce le incompatibilità trai vari browser
  • 7. Fornisce diverse funzioni e oggetti di utilità
  • 8. Permette lo sviluppo di Javascript non intrusivo
  • 9. E' complementare a Script.aculo.us
  • 10. Qualcosa di utile $('...') -> come getDocumentById('...') ma ritorna un Element di Prototype
  • 11. $$('...') -> Selettore CSS $$('.menu #submenu) ritorna tutti gli elementi che hanno class submenu all'interno di un elemento che ha id menu
  • 12. Ajax.request(Url, {...}) -> Esegue una richiesta AJAX, le graffe conterranno le opzioni della request: new Ajax.Request(url, {onSuccess: function(transport) {...}); Esistono anche altri metodi come: updater e periodicalUpdater.
  • 13. Template -> Permette di definire delle stringe parametrizzabili var t = new Template('Name: #{name}, surname: #{surname}'); var show = {name: 'Davide', surname: 'Cerbo'}; t.evaluate(show); //return “Name: Davide, surname: Cerbo”
  • 14. Observer -> Permette di osservare gli eventi su un elemento $('id').observe('click', function(element){...});
  • 15. Di cosa abbiamo bisogno? Per considerare JAVASCRIPT un linguaggio Object Oriented abbiamo bisogno di:
  • 20. Strutture dati complesse Hash -> var h = new Hash(); h.set(“key”, “value”); h.get(“key”); //return “value” h.unset(“key”); h.toQueryString() //return “key1=v1&key2=v2&...”
  • 21. Enumerable -> sono liste iterabili con metodi come each, map, find, select, etc... $A(...).each(function(e){ alert(e.id); }); $$('...') restituisce un Enumerable Sono tutte CLOSURE
  • 22. Questione di classe Javascript Classico var Person = Class.create(); Person.prototype = { initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }; var jack = new Person (“Jack Maffai”); jack.say(“Hi Boy”); //return Jack Maffai: Hi boy! Prototype var Person = Class.create({ initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }); var jack = new Person (“Jack Maffai”); jack.say(“Hi Boy”); //return Jack Maffai: Hi boy!
  • 23. Estendiamo Javascript classico var Pirate = Class.create(); Pirate.prototype = Object.extend(new Person(), { say: function(message) { return this.name + ': ' + message + ', yarr!'; } }); Prototype var Pirate = Class.create(Person, { say: function($super, message) { return $super(message) + ', yarr!'; } }); new Pirate (“Jack Maffai”).say(“Hi Boy!”); //say return: Hi Boy!, yarr!
  • 24. Interfacce? Non ci sono e basta! Accontentiamoci delle classi E ricordiamoci che in Javascript vige la regola: “ If it walks like a duck and quacks like a duck, I would call it a duck.”
  • 25. Al volo var john = new Pirate('Long John'); john.sleep(); // -> ERROR: sleep is not a method Person.addMethods({ sleep: function() { return this.say('ZzZ'); } }); john.sleep(); // -> &quot;Long John: ZzZ, yarr!&quot; Il metodo viene aggiunto a tutte le istanze e le sottoclassi di Pirate
  • 26. DOMinare con Prototype Questo approccio deve cambiare il nostro modo di vedere la programmazione Javascript PROGRAMMAZIONE FUNZIONALE
  • 27. Esempio HTML: <table id=&quot;simonboard&quot;> <TR> <TD id=&quot;red&quot;></TD> <TD id=&quot;blue&quot;></TD> <TD id=&quot;fuchsia&quot;></TD> </TR> <TR> <TD id=&quot;black&quot;></TD> <TD id=&quot;green&quot;></TD> <TD id=&quot;aqua&quot;></TD> </TR> <TR> <TD id=&quot;gold&quot;></TD> <TD id=&quot;magenta&quot;></TD> <TD id=&quot;coral&quot;></TD> </TR> </table> Script di startup: <script language=&quot;JavaScript&quot;> // $('simonboard') -> indica la tabella // 5 -> il numero massimo di quadrati da colorare new Board($('simonboard')).start(5); </script> Il colore predefinito per il quadrato Tabella da utilizzare
  • 28. Lo script var Tile = Class.create({ initialize: function(color, element) { this.color = color; this.element = element; }, blink: function() { this.element.style.backgroundColor = this.color; new Effect.Opacity(this.element, {duration:2, from:1.0, to:0}); // Scrip.aculo.us } }); var Board = Class.create({ initialize: function(boardElement) { this.tiles = boardElement.select(&quot;td&quot;).map(function(element){ return new Tile(element.id, element); }); }, //numero massimo di blocchi da colorare start: function(steps) { var boardSize = this.tiles.length; var tempTiles = this.tiles; //serve per problemi di scope si corregge usando la funzione bind() $R(1, steps).each(function(i){ //funzione di Prototype che riempe un array con un range di valori var index = Math.ceil(Math.random() * boardSize); var tile = tempTiles[index-1]; window.setTimeout(function() { tile.blink(); }, 500 * index); }); } });
  • 29. Un concetto utile: bind start: function(steps) { var boardSize = this.tiles.length; $R(1, steps).each(function(i) { var index = Math.ceil(Math.random() * boardSize); var tile = this.tiles[index-1]; window.setTimeout(function() { tile.blink(); }, 500 * index); } .bind(this) ); } Il bind serve ad evitare problemi di scope, se lo avessi omesso il this considerato dalla funzione sarebbe stato l'oggeto window . In Javascript tutte le funzioni sono eseguite in un determinato contesto e questo è referenziabile tramite la parola chiave da this Le funzioni utilizzate come closure sono funzioni globali, quindi hanno il contesto globale
  • 32. JUnit
  • 33. JMock e simili BlackbirdJS
  • 36. JSMock Siamo abituati ad avere una marea di strumenti a nostra disposione javascript non ci deluderà!
  • 37. Logging: Log4J -> BlackbirdJS
  • 38. Debug: Java Debugger -> Firebug
  • 39. Unit Test: JUnit -> JSUnit [1]
  • 40. Unit Test: JUnit -> JSUnit [2]
  • 41. Unit Test: JUnit -> JSUnit [3]
  • 42. Unit Test: JUnit -> JSUnit [4]
  • 43. MockObject: JMock -> JSMock [1] Classe sotto test (CUT) function Worker() { this.getValue = function() { /* ... */} this.isFinished = function() {/* ... */} } Fixture function doWork(worker) { if(worker.isFinished()) { return worker.getValue(); } else { return null; } } Test function test_doWork() { var mControl = new MockControl(); worker = mControl.createMock(Worker); worker.expects().isFinished().andReturn(true); worker.expects().getValue().andReturn('hello'); var result = doWork(worker); assertEquals('hello', result); mControl.verify(); }
  • 44. MockObject: JMock -> JSMock [2] Classe sotto test (CUT) function Worker() { this.getValue = function() { /* ... */} this.isFinished = function() {/* ... */} } Fixture function doWork(worker) { if(worker.isFinished()) { return worker.getValue(); } else { return null; } } Test function test_doWork_null() { var mControl = new MockControl(); worker = mControl.createMock(Worker); worker.expects().isFinished().andReturn(false); var result = doWork(worker); assertNull(result); mControl.verify(); }
  • 46. Bibliografia & Links www.prototypejs.org
  • 57. Q&A JS? http://jesty.it [email_address] [email_address]