Javascript : fondamentaux et OOP

Jean-Pierre Vincent
Jean-Pierre VincentWeb app expert at braincracking.org
Javascript


Les fondamentaux
      La POO



               Jean-pierre VINCENT
Qui ça ?
       Jean-pierre VINCENT

braincracking.org (veille techno)
@theystolemynick

10 ans de Web
Consultant, formateur, expertise
Javascript : fondamentaux et OOP
Pourquoi Javascript ?
Présent partout
● Navigateur
● Jeux Web (remplace Flash)

● Mobile (Phonegap ...)

● Télévisions

● Serveur (Node.js, ...)

● Software (Chromeless, ...)

● OS (JoliCloud, WebOS...)

● Windows 8 !
Mauvaise réputation
Mauvaise réputation

parseInt('06'); // 6
parseInt('08'); // 0




           wftjs.com
Mauvaise réputation

typeof NaN // number
NaN === NaN // false

typeof null // object
null instanceof Object // false



            wftjs.com
Mauvaise réputation

(1.7976931348623157e+308 ===
 1.7976931348623158e+308 )// true!

 alert(111111111111111111111); //
alerts 111111111111111110000

9999999999999999 //=> 10000000000000000
APIs
●   DOM

●   Node

●   WinRT

...
●
Compliqué ?
Différent !
Historique court
● Né pendant la guerre (95)
● En quelques semaines

● Influence Java, Erlang, Lisp, Python




     IE et Netscape d'accord pour
             EcmaScript 3
Evolution
● EcmaScript 5
● Harmony

● EcmaScript.Next

● EcmaScript.Next.Next
En attendant ...


   EcmaScript 3
Objectif de cette heure

● Savoir deboguer avec 3
fondamentaux


●   Développer Orienté Objet
Notions de base
●   Portée des variables (var + function)

●   Function()

●   Contexte (this)
Portée des variables

         1 closure = 1 portée

Closure = function() {
  PORTÉE
}
Portée des variables
test1 = function() {
  var x = 1;
  test2 = function() {
    var x = 2;
    test3 = function() {
      var x = 3;
     console.log(x); // 3
    }();
  }();
  console.log(x); // 1
}();
console.log(x); // undefined
Boucle infinie !
function genericFunctionName() {
  for(i = 0; i < myArray.length; i++) {
    ....
  }
}

for(i = 0; i < 10; i++) {
  genericFunctionName();
}
Boucle corrigée
function genericFunctionName() {
  for( var i = 0; i<myArray.length;i++){
    ....
  }
}

for(i = 0; i < 10; i++) {
  genericFunctionName();
}
Application pratique
(function() {
  var privateVariable = true;
  function init() {
     console.log( privateVariable );
  }
}())

init(); // true
console.log(privateVariable);//undefined
Créer un scope
1

 function() {
    var privateVariable = true;
    console.log( privateVariable );
 }
 => parse error
Créer un scope
2

( function() {
    var privateVariable = true;
    console.log( privateVariable );
 })
 => rien
Créer un scope
3

( function() {
    var privateVariable = true;
    console.log( privateVariable );
 })()
 => true
Notions de base
✓ Portée des variables (var + function)

●   Function()

●   Contexte (this)
Function()
●   function action() {}


●   action = function() {}


●   action();
function action()

Toujours globale

action(); // true
..
function action() {
  console.log(true);
}
function action()
TROP globale
action(); // a !== 1
if( a === 1) {
  function action() {
    console.log('a === 1');
  }
} else {
  function action() {
     console.log('a !== 1');
  }
}
var action = function()


  Permet de choisir la portée
Peut s'auto-exécuter
autoInit = function() {
    console.log('hello world');
}();
// hello world
return function()
var onDOMEvent =
 function( el, ev, callback) {
  if(document.body.attachEvent){
         el.attachEvent('on'+ev, callback);
  } else {
         el.addEventListener( ev, callback);
     }
};
return function()
var onDOMEvent =
function( el, ev, callback) {
  if(document.body.attachEvent
    return function(el, ev, callback) {
element.attachEvent('on'+event, callback);
   };
  else
       return function(el, ev, callback) {
       el.addEventListener( ev, callback);
       };
}();
Function.prototype
 var myClass = function () {
   this.publicVariable = 0;
};

 myClass.prototype = {
   decrement:function() {
      console.log( --this.publicVariable );
   },
   increment:function() {
      console.log( ++this.publicVariable );
   }
};
Function.prototype
 var myClass = function () {};
 myClass.prototype = {
   decrement:function() {},
   increment:function() {}
};
myObject = new myClass();
myObject.decrement(); // -1
myObject.decrement(); // -2
myObject2 = new myClass();
myObject2.increment(); // 1
myObject2.increment(); // 2
Héritage
mySubClass = function() {
    this.publicVariable = 10;
};
mySubClass.prototype = myClass.prototype;
 mySubClass.prototype.constructor =
mySubClass;

myObject2 = new mySubClass();
myObject2.increment(); // 11
myObject2.increment(); // 12
Renvoi d'objets
myClass = function () {
   var privateVariable = 0;
   // public methods
   return {
     decrement:function() {
       console.log( --privateVariable );
     },
     increment:function() {
       console.log( ++privateVariable );
     }
   }
};
Renvoi d'objets
 myClass = function () {
    return {
      decrement:function() {   },
      increment:function() {   }
    }
 };
myObject = myClass();
myObject.decrement(); // -1
myObject.decrement(); // -2
myObject2 = myClass();
myObject2.increment(); // 1
myObject2.increment(); // 2
Function === Object
myClass = function () {
   return {
     publicMethod:function() {}
   }
};
myClass.staticMethod = function() {};

myObject = myClass();
myObject.staticMethod(); // Error

myClass.publicMethod(); // Error
Portée + déclaration
var queries = [ new XHR('url1'), new
XHR('url2'), new XHR('url3')];

for(var i = 0; i < queries.length; i++) {
  queries[i].onload = function() {
     console.log( i ); // référence
  };
}

queries[ 0 ].onload(); // 3!
queries[ 1 ].onload(); // 3!
queries[ 2 ].onload(); // 3!
Portée + déclaration
for(var i = 0; i < queries.length; i++) {
  queries[i].onload = function(i) {
      return function() {
          console.log( i ); // valeur
      };
  }(i); // exécution immédiate
}
// plus tard ...
queries[ 0 ].onload(); // 0
queries[ 1 ].onload(); // 1
queries[ 2 ].onload(); // 2
Notions de base
✓ Portée des variables (var + function)

✓ Function()

●   Contexte (this)
Contexte


this = contexte d'exécution
Contexte - facile
myClass = function() {
     this.id = 'myClass';
}
myClass.prototype = {
     action:function() {
          console.log(this.id);
     }
};

myObject = new myClass();
myObject.action(); // 'myclass'
Contexte - DOM
myClass = function() {
   this.id = 'myClass';
}
myClass.prototype = {
   action:function() {
   console.log(this.id);
   }
};
myObject = new myClass();
document.body.onclick = myObject.action;

// document.body.id
Contexte – tous objets
myClass = function() {
   this.id = 'myClass';
}
myClass.prototype = {
   action:function() {
   console.log(this.id);
   }
};
myObject = new myClass();
myEvent = {
     id:'myObj2'
}
myEvent.onfire = myObj.action;
myEvent.onfire(); // myObj2
Contexte – fix natif
myClass = function() {
   this.id = 'myClass';
}
myClass.prototype = {
   action:function() {
   console.log(this.id);
   }
};
myObject = new myClass();
myEvent = {
     id:'myObj2'
}
myEvent.onfire = myObj.action;
myEvent.onfire.call( myObject ); // myClass
Contexte: sans prototype
myClass = function() {
   this.id = 'myClass';
   var me = this;
   return {
     action:function() {
       console.log(me.id);
     }
   }
};
 myObject = myClass();
 document.body.onclick = myObject.action;
 // 'myClass'
Notions de base
✓ Portée des variables (var + function)

✓ Function()

✓ Contexte (this)
Développement durable

●   Pollution du scope global


●   Programmation Orienté Objet
Pollution globale
Pollution globale
    2 exemples complètement au hasard
●Gmail : 33 variables globales (450K lignes
de code)


●   Lemonde.fr : 480 variables globales
Actions
✗ Function action() {}

✓ var action = function() {
      var myVariable;
  }

✓namespaces
Namespaces
var MY_APP_NAMESPACE = {};

MY.doSomething = function() {};

MY.utils = {};

MY.utils.XHR = function() {

}
Namespaces - astuce
récupérer ou créer un namespace
MY = windows.MY || {};

MY.utils = MY.utils || {};
Création d'un scope
Rappel

(function(){ // début de scope local
    var private = true;

// ici je suis chez moi

})(); // fin de scope local
Programmation
Orienté
Objet
Tout est objet
"abc".indexOf('a');

[1,2,3].slice(1);

13.3714 .toFixed(1);

/[0-9]/g.test('10/11/2011');
POO Classique
 new, class, static,
public, private,
__construct, $this, const,
self::, extends, protected,
parent::, abstract, final,
interface, implements,
instanceof
POO JS

new (optionel)
this (particulier)
instanceof
Interface publique
(function(){ // début de scope local

 // accès global au constructeur
 MY.utils.XHR = function( url ) {
    this.url = url;
 };
 // méthodes ou variable statiques
 MY.utils.XHR.staticVariable = true;

})(); // fin de scope local
Raccourci
(function(){ // début de scope local

 // raccourci vers le namespace
utilisé
   var self = MY.utils.XHR;

  self.staticVariable = true;



})(); // fin de scope local
privées communes
(function(){ // début de scope local

// accès global au constructeur
MY.utils.XHR = function( url ) {
   this.url = url;
   currentInstances.push( this );
};
var currentInstances = [];


})(); // fin de scope local
privées par instance
(function(){ // début de scope local
// accès global au constructeur
MY.utils.XHR = function( url ) {
   var isConnecting = true;
   return {
     query:function() {
       if( isConnecting)
         return false;
     }
   }
};
})(); // fin de scope local
Combo : factory pattern
(function(){
MY.utils.XHR = function( ) {
   throw new Error( 'please use .getInstance()' );
};
// constructeur privé
var XHR = function(url) { console.log(url); };
// liste privée
var currentInstances = {};
// factory
MY.utils.XHR.getInstance = function( url ) {
   if(currentInstances[url])
     return currentInstances[url];
   else
     return currentInstances[url] = new XHR( url);
}
})();
Tout est émulable
●   programmation événementielle

●   tests unitaires et fonctionnels

● patterns classiques : MVC, observer,
facade, proxy, singleton, factory ...
Conclusion

●   Javascript est différent, apprenez le

●   OOP réutilisable
Questions ?


Jean-pierre VINCENT
braincracking.org
@theystolemynick
1 of 68

Recommended

20140123 java8 lambdas_jose-paumard-soat by
20140123 java8 lambdas_jose-paumard-soat20140123 java8 lambdas_jose-paumard-soat
20140123 java8 lambdas_jose-paumard-soatSOAT
1.1K views271 slides
Découverte du moteur de rendu du projet Spartan by
Découverte du moteur de rendu du projet SpartanDécouverte du moteur de rendu du projet Spartan
Découverte du moteur de rendu du projet SpartanMicrosoft
2.3K views42 slides
Introduction au Jquery by
Introduction au JqueryIntroduction au Jquery
Introduction au JqueryAbdoulaye Dieng
818 views19 slides
Symfony2 - Un Framework PHP 5 Performant by
Symfony2 - Un Framework PHP 5 PerformantSymfony2 - Un Framework PHP 5 Performant
Symfony2 - Un Framework PHP 5 PerformantHugo Hamon
3.1K views64 slides
Procédures CLR pour SQL Server : avantages et inconvénients by
Procédures CLR pour SQL Server : avantages et inconvénientsProcédures CLR pour SQL Server : avantages et inconvénients
Procédures CLR pour SQL Server : avantages et inconvénientsDenis Voituron
855 views23 slides
Python avancé : Tuple et objet by
Python avancé : Tuple et objetPython avancé : Tuple et objet
Python avancé : Tuple et objetECAM Brussels Engineering School
2K views35 slides

More Related Content

What's hot

jQuery — fonctionnalités avancées by
jQuery — fonctionnalités avancéesjQuery — fonctionnalités avancées
jQuery — fonctionnalités avancéesRémi Prévost
4.3K views134 slides
Programmation orientée objet : Object, classe et encapsulation by
Programmation orientée objet : Object, classe et encapsulationProgrammation orientée objet : Object, classe et encapsulation
Programmation orientée objet : Object, classe et encapsulationECAM Brussels Engineering School
1.6K views40 slides
Requêtes HTTP synchrones et asynchrones by
Requêtes HTTPsynchrones et asynchronesRequêtes HTTPsynchrones et asynchrones
Requêtes HTTP synchrones et asynchronesAbdoulaye Dieng
5.7K views29 slides
Programmation fonctionnelle by
Programmation fonctionnelleProgrammation fonctionnelle
Programmation fonctionnelleGeeks Anonymes
1.2K views46 slides
Asyncio: offrez des tulipes à vos entrées sorties asynchrones by
Asyncio: offrez des tulipes à vos entrées sorties asynchronesAsyncio: offrez des tulipes à vos entrées sorties asynchrones
Asyncio: offrez des tulipes à vos entrées sorties asynchronestchappui
582 views33 slides
Solution Linux 2009 JavaScript by
Solution Linux 2009 JavaScriptSolution Linux 2009 JavaScript
Solution Linux 2009 JavaScriptRaphaël Semeteys
355 views12 slides

What's hot(20)

jQuery — fonctionnalités avancées by Rémi Prévost
jQuery — fonctionnalités avancéesjQuery — fonctionnalités avancées
jQuery — fonctionnalités avancées
Rémi Prévost4.3K views
Requêtes HTTP synchrones et asynchrones by Abdoulaye Dieng
Requêtes HTTPsynchrones et asynchronesRequêtes HTTPsynchrones et asynchrones
Requêtes HTTP synchrones et asynchrones
Abdoulaye Dieng5.7K views
Programmation fonctionnelle by Geeks Anonymes
Programmation fonctionnelleProgrammation fonctionnelle
Programmation fonctionnelle
Geeks Anonymes1.2K views
Asyncio: offrez des tulipes à vos entrées sorties asynchrones by tchappui
Asyncio: offrez des tulipes à vos entrées sorties asynchronesAsyncio: offrez des tulipes à vos entrées sorties asynchrones
Asyncio: offrez des tulipes à vos entrées sorties asynchrones
tchappui582 views
Java 8 : Un ch'ti peu de lambda by Ch'ti JUG
Java 8 : Un ch'ti peu de lambdaJava 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambda
Ch'ti JUG5.4K views
Comprendre les scripts shell auto-extractible by Thierry Gayet
Comprendre les scripts shell auto-extractibleComprendre les scripts shell auto-extractible
Comprendre les scripts shell auto-extractible
Thierry Gayet654 views
Modèle de domaine riche dans une application métier complexe un exemple pratique by Vladyslav Riabchenko
Modèle de domaine riche dans une application métier complexe un exemple pratiqueModèle de domaine riche dans une application métier complexe un exemple pratique
Modèle de domaine riche dans une application métier complexe un exemple pratique

Viewers also liked

Reasoning about laziness by
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
3.7K views29 slides
bluespec talk by
bluespec talkbluespec talk
bluespec talkSuman Karumuri
2K views54 slides
Le monitoring de la performance front by
Le monitoring de la performance frontLe monitoring de la performance front
Le monitoring de la performance frontJean-Pierre Vincent
2.2K views35 slides
Soirée webperf du 29 nov 2010 - Latence et CDN by
Soirée webperf du 29 nov 2010 - Latence et CDNSoirée webperf du 29 nov 2010 - Latence et CDN
Soirée webperf du 29 nov 2010 - Latence et CDNEric D.
1.5K views15 slides
Your data structures are made of maths! by
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!kenbot
6.1K views196 slides
Cloud Technology and Its Implication for Quality Services by
Cloud Technology and Its Implication for Quality ServicesCloud Technology and Its Implication for Quality Services
Cloud Technology and Its Implication for Quality ServicesSparta Systems
14.2K views17 slides

Viewers also liked(20)

Reasoning about laziness by Johan Tibell
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
Johan Tibell3.7K views
Soirée webperf du 29 nov 2010 - Latence et CDN by Eric D.
Soirée webperf du 29 nov 2010 - Latence et CDNSoirée webperf du 29 nov 2010 - Latence et CDN
Soirée webperf du 29 nov 2010 - Latence et CDN
Eric D.1.5K views
Your data structures are made of maths! by kenbot
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!
kenbot6.1K views
Cloud Technology and Its Implication for Quality Services by Sparta Systems
Cloud Technology and Its Implication for Quality ServicesCloud Technology and Its Implication for Quality Services
Cloud Technology and Its Implication for Quality Services
Sparta Systems14.2K views
Intro to @viewport & other new Responsive Web Design CSS features by Andreas Bovens
Intro to @viewport & other new Responsive Web Design CSS featuresIntro to @viewport & other new Responsive Web Design CSS features
Intro to @viewport & other new Responsive Web Design CSS features
Andreas Bovens20.6K views
Progressive Enhancement 2.0 (Conference Agnostic) by Nicholas Zakas
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
Nicholas Zakas42.5K views
Functional Programming Patterns (NDC London 2014) by Scott Wlaschin
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
Scott Wlaschin262.1K views
Domain Modeling in a Functional World by Debasish Ghosh
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional World
Debasish Ghosh50.6K views
Functional Programming in JavaScript by Luis Atencio by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
Luis Atencio7.2K views
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu... by Chris Richardson
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Chris Richardson12.8K views
Who's More Functional: Kotlin, Groovy, Scala, or Java? by Andrey Breslav
Who's More Functional: Kotlin, Groovy, Scala, or Java?Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?
Andrey Breslav15.3K views
Intro to Functional Programming by Hugo Firth
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
Hugo Firth4.9K views
Introduction to Functional Programming in JavaScript by tmont
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont9.1K views
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter... by Domenic Denicola
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola184.2K views
"Немного о функциональном программирование в JavaScript" Алексей Коваленко by Fwdays
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays4.5K views

Similar to Javascript : fondamentaux et OOP

Introduction à JavaScript by
Introduction à JavaScriptIntroduction à JavaScript
Introduction à JavaScriptMicrosoft
762 views51 slides
Fondamentaux portée - contexte - function ms tech days by
Fondamentaux   portée - contexte - function ms tech daysFondamentaux   portée - contexte - function ms tech days
Fondamentaux portée - contexte - function ms tech daysJean-Pierre Vincent
1.3K views51 slides
Function oop - bonnes pratiques ms tech days by
Function   oop - bonnes pratiques ms tech daysFunction   oop - bonnes pratiques ms tech days
Function oop - bonnes pratiques ms tech daysJean-Pierre Vincent
853 views67 slides
Patterns et bonnes pratiques autour de JavaScript by
Patterns et bonnes pratiques autour de JavaScriptPatterns et bonnes pratiques autour de JavaScript
Patterns et bonnes pratiques autour de JavaScriptMicrosoft Technet France
1K views67 slides
Javascript ne se limite pas à jquery by
Javascript ne se limite pas à jqueryJavascript ne se limite pas à jquery
Javascript ne se limite pas à jqueryneuros
762 views45 slides
JavaScript prise en main et fondamentaux by
JavaScript prise en main et fondamentauxJavaScript prise en main et fondamentaux
JavaScript prise en main et fondamentauxVincent Petetin
668 views10 slides

Similar to Javascript : fondamentaux et OOP(20)

Introduction à JavaScript by Microsoft
Introduction à JavaScriptIntroduction à JavaScript
Introduction à JavaScript
Microsoft762 views
Fondamentaux portée - contexte - function ms tech days by Jean-Pierre Vincent
Fondamentaux   portée - contexte - function ms tech daysFondamentaux   portée - contexte - function ms tech days
Fondamentaux portée - contexte - function ms tech days
Jean-Pierre Vincent1.3K views
Javascript ne se limite pas à jquery by neuros
Javascript ne se limite pas à jqueryJavascript ne se limite pas à jquery
Javascript ne se limite pas à jquery
neuros762 views
JavaScript prise en main et fondamentaux by Vincent Petetin
JavaScript prise en main et fondamentauxJavaScript prise en main et fondamentaux
JavaScript prise en main et fondamentaux
Vincent Petetin668 views
GWT : under the hood by svuillet
GWT : under the hoodGWT : under the hood
GWT : under the hood
svuillet4.5K views
Présentation de ECMAScript 6 by Julien CROUZET
Présentation de ECMAScript 6Présentation de ECMAScript 6
Présentation de ECMAScript 6
Julien CROUZET2.9K views
Nouveautés JavaScript dans le monde Microsoft by davrous
Nouveautés JavaScript dans le monde MicrosoftNouveautés JavaScript dans le monde Microsoft
Nouveautés JavaScript dans le monde Microsoft
davrous2.4K views
Quelle place pour le framework Rails dans le développement d'application web by 5pidou
Quelle place pour le framework Rails dans le développement d'application webQuelle place pour le framework Rails dans le développement d'application web
Quelle place pour le framework Rails dans le développement d'application web
5pidou594 views
Fork / Join, Parallel Arrays, Lambdas : la programmation parallèle (trop ?) f... by Normandy JUG
Fork / Join, Parallel Arrays, Lambdas : la programmation parallèle (trop ?) f...Fork / Join, Parallel Arrays, Lambdas : la programmation parallèle (trop ?) f...
Fork / Join, Parallel Arrays, Lambdas : la programmation parallèle (trop ?) f...
Normandy JUG1.8K views
Javascript pour les développeurs Java : quels sont les pièges à éviter ? by FlorianBoulay
Javascript pour les développeurs Java : quels sont les pièges à éviter ?Javascript pour les développeurs Java : quels sont les pièges à éviter ?
Javascript pour les développeurs Java : quels sont les pièges à éviter ?
FlorianBoulay6.9K views
Javascript Json artchitecture by zaghir
Javascript  Json artchitecture Javascript  Json artchitecture
Javascript Json artchitecture
zaghir92 views
Meetup#1 talk#1 by neopixl
Meetup#1 talk#1Meetup#1 talk#1
Meetup#1 talk#1
neopixl112 views

More from Jean-Pierre Vincent

Mesurer la performance : onload, pages by
Mesurer la performance : onload, pagesMesurer la performance : onload, pages
Mesurer la performance : onload, pagesJean-Pierre Vincent
960 views39 slides
Les Performance de rendu sur mobile by
Les Performance de rendu sur mobileLes Performance de rendu sur mobile
Les Performance de rendu sur mobileJean-Pierre Vincent
2.2K views43 slides
La performance sur mobile by
La performance sur mobileLa performance sur mobile
La performance sur mobileJean-Pierre Vincent
1.9K views45 slides
Performances web - quoi de neuf ? by
Performances web - quoi de neuf ?Performances web - quoi de neuf ?
Performances web - quoi de neuf ?Jean-Pierre Vincent
5.4K views24 slides
Accélération des pages Web : les bases en exemple by
Accélération des pages Web : les bases en exempleAccélération des pages Web : les bases en exemple
Accélération des pages Web : les bases en exempleJean-Pierre Vincent
1.7K views45 slides
Introduction à la webperf by
Introduction à la webperfIntroduction à la webperf
Introduction à la webperfJean-Pierre Vincent
1.9K views57 slides

More from Jean-Pierre Vincent(17)

Accélération des pages Web : les bases en exemple by Jean-Pierre Vincent
Accélération des pages Web : les bases en exempleAccélération des pages Web : les bases en exemple
Accélération des pages Web : les bases en exemple
Jean-Pierre Vincent1.7K views
Techniques accélération des pages web #kiwiparty by Jean-Pierre Vincent
Techniques accélération des pages web #kiwipartyTechniques accélération des pages web #kiwiparty
Techniques accélération des pages web #kiwiparty
Jean-Pierre Vincent5.1K views
Inclure du Javascript de manière performante by Jean-Pierre Vincent
Inclure du Javascript de manière performanteInclure du Javascript de manière performante
Inclure du Javascript de manière performante
Jean-Pierre Vincent1.9K views

Javascript : fondamentaux et OOP

  • 1. Javascript Les fondamentaux La POO Jean-pierre VINCENT
  • 2. Qui ça ? Jean-pierre VINCENT braincracking.org (veille techno) @theystolemynick 10 ans de Web Consultant, formateur, expertise
  • 5. Présent partout ● Navigateur ● Jeux Web (remplace Flash) ● Mobile (Phonegap ...) ● Télévisions ● Serveur (Node.js, ...) ● Software (Chromeless, ...) ● OS (JoliCloud, WebOS...) ● Windows 8 !
  • 7. Mauvaise réputation parseInt('06'); // 6 parseInt('08'); // 0 wftjs.com
  • 8. Mauvaise réputation typeof NaN // number NaN === NaN // false typeof null // object null instanceof Object // false wftjs.com
  • 9. Mauvaise réputation (1.7976931348623157e+308 === 1.7976931348623158e+308 )// true! alert(111111111111111111111); // alerts 111111111111111110000 9999999999999999 //=> 10000000000000000
  • 10. APIs ● DOM ● Node ● WinRT ... ●
  • 13. Historique court ● Né pendant la guerre (95) ● En quelques semaines ● Influence Java, Erlang, Lisp, Python IE et Netscape d'accord pour EcmaScript 3
  • 14. Evolution ● EcmaScript 5 ● Harmony ● EcmaScript.Next ● EcmaScript.Next.Next
  • 15. En attendant ... EcmaScript 3
  • 16. Objectif de cette heure ● Savoir deboguer avec 3 fondamentaux ● Développer Orienté Objet
  • 17. Notions de base ● Portée des variables (var + function) ● Function() ● Contexte (this)
  • 18. Portée des variables 1 closure = 1 portée Closure = function() { PORTÉE }
  • 19. Portée des variables test1 = function() { var x = 1; test2 = function() { var x = 2; test3 = function() { var x = 3; console.log(x); // 3 }(); }(); console.log(x); // 1 }(); console.log(x); // undefined
  • 20. Boucle infinie ! function genericFunctionName() { for(i = 0; i < myArray.length; i++) { .... } } for(i = 0; i < 10; i++) { genericFunctionName(); }
  • 21. Boucle corrigée function genericFunctionName() { for( var i = 0; i<myArray.length;i++){ .... } } for(i = 0; i < 10; i++) { genericFunctionName(); }
  • 22. Application pratique (function() { var privateVariable = true; function init() { console.log( privateVariable ); } }()) init(); // true console.log(privateVariable);//undefined
  • 23. Créer un scope 1 function() { var privateVariable = true; console.log( privateVariable ); } => parse error
  • 24. Créer un scope 2 ( function() { var privateVariable = true; console.log( privateVariable ); }) => rien
  • 25. Créer un scope 3 ( function() { var privateVariable = true; console.log( privateVariable ); })() => true
  • 26. Notions de base ✓ Portée des variables (var + function) ● Function() ● Contexte (this)
  • 27. Function() ● function action() {} ● action = function() {} ● action();
  • 28. function action() Toujours globale action(); // true .. function action() { console.log(true); }
  • 29. function action() TROP globale action(); // a !== 1 if( a === 1) { function action() { console.log('a === 1'); } } else { function action() { console.log('a !== 1'); } }
  • 30. var action = function() Permet de choisir la portée
  • 31. Peut s'auto-exécuter autoInit = function() { console.log('hello world'); }(); // hello world
  • 32. return function() var onDOMEvent = function( el, ev, callback) { if(document.body.attachEvent){ el.attachEvent('on'+ev, callback); } else { el.addEventListener( ev, callback); } };
  • 33. return function() var onDOMEvent = function( el, ev, callback) { if(document.body.attachEvent return function(el, ev, callback) { element.attachEvent('on'+event, callback); }; else return function(el, ev, callback) { el.addEventListener( ev, callback); }; }();
  • 34. Function.prototype var myClass = function () { this.publicVariable = 0; }; myClass.prototype = { decrement:function() { console.log( --this.publicVariable ); }, increment:function() { console.log( ++this.publicVariable ); } };
  • 35. Function.prototype var myClass = function () {}; myClass.prototype = { decrement:function() {}, increment:function() {} }; myObject = new myClass(); myObject.decrement(); // -1 myObject.decrement(); // -2 myObject2 = new myClass(); myObject2.increment(); // 1 myObject2.increment(); // 2
  • 36. Héritage mySubClass = function() { this.publicVariable = 10; }; mySubClass.prototype = myClass.prototype; mySubClass.prototype.constructor = mySubClass; myObject2 = new mySubClass(); myObject2.increment(); // 11 myObject2.increment(); // 12
  • 37. Renvoi d'objets myClass = function () { var privateVariable = 0; // public methods return { decrement:function() { console.log( --privateVariable ); }, increment:function() { console.log( ++privateVariable ); } } };
  • 38. Renvoi d'objets myClass = function () { return { decrement:function() { }, increment:function() { } } }; myObject = myClass(); myObject.decrement(); // -1 myObject.decrement(); // -2 myObject2 = myClass(); myObject2.increment(); // 1 myObject2.increment(); // 2
  • 39. Function === Object myClass = function () { return { publicMethod:function() {} } }; myClass.staticMethod = function() {}; myObject = myClass(); myObject.staticMethod(); // Error myClass.publicMethod(); // Error
  • 40. Portée + déclaration var queries = [ new XHR('url1'), new XHR('url2'), new XHR('url3')]; for(var i = 0; i < queries.length; i++) { queries[i].onload = function() { console.log( i ); // référence }; } queries[ 0 ].onload(); // 3! queries[ 1 ].onload(); // 3! queries[ 2 ].onload(); // 3!
  • 41. Portée + déclaration for(var i = 0; i < queries.length; i++) { queries[i].onload = function(i) { return function() { console.log( i ); // valeur }; }(i); // exécution immédiate } // plus tard ... queries[ 0 ].onload(); // 0 queries[ 1 ].onload(); // 1 queries[ 2 ].onload(); // 2
  • 42. Notions de base ✓ Portée des variables (var + function) ✓ Function() ● Contexte (this)
  • 43. Contexte this = contexte d'exécution
  • 44. Contexte - facile myClass = function() { this.id = 'myClass'; } myClass.prototype = { action:function() { console.log(this.id); } }; myObject = new myClass(); myObject.action(); // 'myclass'
  • 45. Contexte - DOM myClass = function() { this.id = 'myClass'; } myClass.prototype = { action:function() { console.log(this.id); } }; myObject = new myClass(); document.body.onclick = myObject.action; // document.body.id
  • 46. Contexte – tous objets myClass = function() { this.id = 'myClass'; } myClass.prototype = { action:function() { console.log(this.id); } }; myObject = new myClass(); myEvent = { id:'myObj2' } myEvent.onfire = myObj.action; myEvent.onfire(); // myObj2
  • 47. Contexte – fix natif myClass = function() { this.id = 'myClass'; } myClass.prototype = { action:function() { console.log(this.id); } }; myObject = new myClass(); myEvent = { id:'myObj2' } myEvent.onfire = myObj.action; myEvent.onfire.call( myObject ); // myClass
  • 48. Contexte: sans prototype myClass = function() { this.id = 'myClass'; var me = this; return { action:function() { console.log(me.id); } } }; myObject = myClass(); document.body.onclick = myObject.action; // 'myClass'
  • 49. Notions de base ✓ Portée des variables (var + function) ✓ Function() ✓ Contexte (this)
  • 50. Développement durable ● Pollution du scope global ● Programmation Orienté Objet
  • 52. Pollution globale 2 exemples complètement au hasard ●Gmail : 33 variables globales (450K lignes de code) ● Lemonde.fr : 480 variables globales
  • 53. Actions ✗ Function action() {} ✓ var action = function() { var myVariable; } ✓namespaces
  • 54. Namespaces var MY_APP_NAMESPACE = {}; MY.doSomething = function() {}; MY.utils = {}; MY.utils.XHR = function() { }
  • 55. Namespaces - astuce récupérer ou créer un namespace MY = windows.MY || {}; MY.utils = MY.utils || {};
  • 56. Création d'un scope Rappel (function(){ // début de scope local var private = true; // ici je suis chez moi })(); // fin de scope local
  • 58. Tout est objet "abc".indexOf('a'); [1,2,3].slice(1); 13.3714 .toFixed(1); /[0-9]/g.test('10/11/2011');
  • 59. POO Classique new, class, static, public, private, __construct, $this, const, self::, extends, protected, parent::, abstract, final, interface, implements, instanceof
  • 60. POO JS new (optionel) this (particulier) instanceof
  • 61. Interface publique (function(){ // début de scope local // accès global au constructeur MY.utils.XHR = function( url ) { this.url = url; }; // méthodes ou variable statiques MY.utils.XHR.staticVariable = true; })(); // fin de scope local
  • 62. Raccourci (function(){ // début de scope local // raccourci vers le namespace utilisé var self = MY.utils.XHR; self.staticVariable = true; })(); // fin de scope local
  • 63. privées communes (function(){ // début de scope local // accès global au constructeur MY.utils.XHR = function( url ) { this.url = url; currentInstances.push( this ); }; var currentInstances = []; })(); // fin de scope local
  • 64. privées par instance (function(){ // début de scope local // accès global au constructeur MY.utils.XHR = function( url ) { var isConnecting = true; return { query:function() { if( isConnecting) return false; } } }; })(); // fin de scope local
  • 65. Combo : factory pattern (function(){ MY.utils.XHR = function( ) { throw new Error( 'please use .getInstance()' ); }; // constructeur privé var XHR = function(url) { console.log(url); }; // liste privée var currentInstances = {}; // factory MY.utils.XHR.getInstance = function( url ) { if(currentInstances[url]) return currentInstances[url]; else return currentInstances[url] = new XHR( url); } })();
  • 66. Tout est émulable ● programmation événementielle ● tests unitaires et fonctionnels ● patterns classiques : MVC, observer, facade, proxy, singleton, factory ...
  • 67. Conclusion ● Javascript est différent, apprenez le ● OOP réutilisable