SlideShare ist ein Scribd-Unternehmen logo
1 von 68
Downloaden Sie, um offline zu lesen
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

jQuery — fonctionnalités avancées
jQuery — fonctionnalités avancéesjQuery — fonctionnalités avancées
jQuery — fonctionnalités avancéesRémi Prévost
 
Programmation orientée objet : Object, classe et encapsulation
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
 
Requêtes HTTP synchrones et asynchrones
Requêtes HTTPsynchrones et asynchronesRequêtes HTTPsynchrones et asynchrones
Requêtes HTTP synchrones et asynchronesAbdoulaye Dieng
 
Programmation fonctionnelle
Programmation fonctionnelleProgrammation fonctionnelle
Programmation fonctionnelleGeeks Anonymes
 
Asyncio: offrez des tulipes à vos entrées sorties asynchrones
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
 
Solution Linux 2009 - JavaScript
Solution Linux 2009 - JavaScriptSolution Linux 2009 - JavaScript
Solution Linux 2009 - JavaScriptRaphaël Semeteys
 
Développement informatique : Programmation fonctionnelle, décorateur et génér...
Développement informatique : Programmation fonctionnelle, décorateur et génér...Développement informatique : Programmation fonctionnelle, décorateur et génér...
Développement informatique : Programmation fonctionnelle, décorateur et génér...ECAM Brussels Engineering School
 
Java (8) eXperiments - DevoxxFR 2016
Java (8) eXperiments - DevoxxFR 2016Java (8) eXperiments - DevoxxFR 2016
Java (8) eXperiments - DevoxxFR 2016François Sarradin
 
Introduction à React JS
Introduction à React JSIntroduction à React JS
Introduction à React JSAbdoulaye Dieng
 
Développement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulièresDéveloppement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulièresECAM Brussels Engineering School
 
Python avancé : Gestion d'erreurs et mécanisme d'exception
Python avancé : Gestion d'erreurs et mécanisme d'exceptionPython avancé : Gestion d'erreurs et mécanisme d'exception
Python avancé : Gestion d'erreurs et mécanisme d'exceptionECAM Brussels Engineering School
 
Java 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambdaJava 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambdaCh'ti JUG
 
Comprendre les scripts shell auto-extractible
Comprendre les scripts shell auto-extractibleComprendre les scripts shell auto-extractible
Comprendre les scripts shell auto-extractibleThierry Gayet
 
Python avancé : Interface graphique et programmation évènementielle
Python avancé : Interface graphique et programmation évènementiellePython avancé : Interface graphique et programmation évènementielle
Python avancé : Interface graphique et programmation évènementielleECAM Brussels Engineering School
 
Modè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 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 pratiqueVladyslav Riabchenko
 

Was ist angesagt? (20)

jQuery — fonctionnalités avancées
jQuery — fonctionnalités avancéesjQuery — fonctionnalités avancées
jQuery — fonctionnalités avancées
 
Programmation orientée objet : Object, classe et encapsulation
Programmation orientée objet : Object, classe et encapsulationProgrammation orientée objet : Object, classe et encapsulation
Programmation orientée objet : Object, classe et encapsulation
 
Requêtes HTTP synchrones et asynchrones
Requêtes HTTPsynchrones et asynchronesRequêtes HTTPsynchrones et asynchrones
Requêtes HTTP synchrones et asynchrones
 
Programmation fonctionnelle
Programmation fonctionnelleProgrammation fonctionnelle
Programmation fonctionnelle
 
Asyncio: offrez des tulipes à vos entrées sorties asynchrones
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
 
Solution Linux 2009 - JavaScript
Solution Linux 2009 - JavaScriptSolution Linux 2009 - JavaScript
Solution Linux 2009 - JavaScript
 
Programmation Fonctionnelle
Programmation FonctionnelleProgrammation Fonctionnelle
Programmation Fonctionnelle
 
Introduction à ajax
Introduction à ajaxIntroduction à ajax
Introduction à ajax
 
Développement informatique : Programmation fonctionnelle, décorateur et génér...
Développement informatique : Programmation fonctionnelle, décorateur et génér...Développement informatique : Programmation fonctionnelle, décorateur et génér...
Développement informatique : Programmation fonctionnelle, décorateur et génér...
 
Java (8) eXperiments - DevoxxFR 2016
Java (8) eXperiments - DevoxxFR 2016Java (8) eXperiments - DevoxxFR 2016
Java (8) eXperiments - DevoxxFR 2016
 
Introduction à React JS
Introduction à React JSIntroduction à React JS
Introduction à React JS
 
Ruby STAR
Ruby STARRuby STAR
Ruby STAR
 
Développement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulièresDéveloppement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulières
 
Présentation nouveauté java7
Présentation nouveauté java7Présentation nouveauté java7
Présentation nouveauté java7
 
Algo poo ts
Algo poo tsAlgo poo ts
Algo poo ts
 
Python avancé : Gestion d'erreurs et mécanisme d'exception
Python avancé : Gestion d'erreurs et mécanisme d'exceptionPython avancé : Gestion d'erreurs et mécanisme d'exception
Python avancé : Gestion d'erreurs et mécanisme d'exception
 
Java 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambdaJava 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambda
 
Comprendre les scripts shell auto-extractible
Comprendre les scripts shell auto-extractibleComprendre les scripts shell auto-extractible
Comprendre les scripts shell auto-extractible
 
Python avancé : Interface graphique et programmation évènementielle
Python avancé : Interface graphique et programmation évènementiellePython avancé : Interface graphique et programmation évènementielle
Python avancé : Interface graphique et programmation évènementielle
 
Modè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 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
 

Andere mochten auch

Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
 
Le monitoring de la performance front
Le monitoring de la performance frontLe monitoring de la performance front
Le monitoring de la performance frontJean-Pierre Vincent
 
Soirée webperf du 29 nov 2010 - Latence et CDN
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.
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!kenbot
 
Cloud Technology and Its Implication for Quality Services
Cloud Technology and Its Implication for Quality ServicesCloud Technology and Its Implication for Quality Services
Cloud Technology and Its Implication for Quality ServicesSparta Systems
 
Intro to @viewport & other new Responsive Web Design CSS features
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 featuresAndreas Bovens
 
Why ARIA? [DevChatt 2010]
Why ARIA? [DevChatt 2010]Why ARIA? [DevChatt 2010]
Why ARIA? [DevChatt 2010]Aaron Gustafson
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Nicholas Zakas
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional WorldDebasish Ghosh
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
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...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Chris Richardson
 
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?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Andrey Breslav
 
Анонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита ВолковАнонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита ВолковЮрий Сыровецкий
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingHugo Firth
 
Монады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон ХоломьёвМонады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон ХоломьёвЮрий Сыровецкий
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScripttmont
 
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...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 

Andere mochten auch (20)

Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
bluespec talk
bluespec talkbluespec talk
bluespec talk
 
Le monitoring de la performance front
Le monitoring de la performance frontLe monitoring de la performance front
Le monitoring de la performance front
 
Soirée webperf du 29 nov 2010 - Latence et CDN
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
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!
 
Cloud Technology and Its Implication for Quality Services
Cloud Technology and Its Implication for Quality ServicesCloud Technology and Its Implication for Quality Services
Cloud Technology and Its Implication for Quality Services
 
Intro to @viewport & other new Responsive Web Design CSS features
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
 
Why ARIA? [DevChatt 2010]
Why ARIA? [DevChatt 2010]Why ARIA? [DevChatt 2010]
Why ARIA? [DevChatt 2010]
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional World
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
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...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
 
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?
Who's More Functional: Kotlin, Groovy, Scala, or Java?
 
Анонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита ВолковАнонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита Волков
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Монады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон ХоломьёвМонады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон Холомьёв
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
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...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 

Ähnlich wie Javascript : fondamentaux et OOP

Introduction à JavaScript
Introduction à JavaScriptIntroduction à JavaScript
Introduction à JavaScriptMicrosoft
 
Fondamentaux portée - contexte - function ms tech days
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
 
Function oop - bonnes pratiques ms tech days
Function   oop - bonnes pratiques ms tech daysFunction   oop - bonnes pratiques ms tech days
Function oop - bonnes pratiques ms tech daysJean-Pierre Vincent
 
Patterns et bonnes pratiques autour de JavaScript
Patterns et bonnes pratiques autour de JavaScriptPatterns et bonnes pratiques autour de JavaScript
Patterns et bonnes pratiques autour de JavaScriptMicrosoft Technet France
 
Javascript ne se limite pas à jquery
Javascript ne se limite pas à jqueryJavascript ne se limite pas à jquery
Javascript ne se limite pas à jqueryneuros
 
JavaScript prise en main et fondamentaux
JavaScript prise en main et fondamentauxJavaScript prise en main et fondamentaux
JavaScript prise en main et fondamentauxVincent Petetin
 
Présentation Javascript à l'ESI (Alger)
Présentation Javascript à l'ESI (Alger)Présentation Javascript à l'ESI (Alger)
Présentation Javascript à l'ESI (Alger)Dr Samir A. ROUABHI
 
GWT : under the hood
GWT : under the hoodGWT : under the hood
GWT : under the hoodsvuillet
 
Présentation de ECMAScript 6
Présentation de ECMAScript 6Présentation de ECMAScript 6
Présentation de ECMAScript 6Julien CROUZET
 
Nouveautés JavaScript dans le monde Microsoft
Nouveautés JavaScript dans le monde MicrosoftNouveautés JavaScript dans le monde Microsoft
Nouveautés JavaScript dans le monde Microsoftdavrous
 
Quelle place pour le framework Rails dans le développement d'application web
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 web5pidou
 
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...
Fork / Join, Parallel Arrays, Lambdas : la programmation parallèle (trop ?) f...Normandy JUG
 
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 ?
Javascript pour les développeurs Java : quels sont les pièges à éviter ?FlorianBoulay
 
Javascript Json artchitecture
Javascript  Json artchitecture Javascript  Json artchitecture
Javascript Json artchitecture zaghir
 
Meetup#1 talk#1
Meetup#1 talk#1Meetup#1 talk#1
Meetup#1 talk#1neopixl
 

Ähnlich wie Javascript : fondamentaux et OOP (20)

Introduction à JavaScript
Introduction à JavaScriptIntroduction à JavaScript
Introduction à JavaScript
 
Fondamentaux portée - contexte - function ms tech days
Fondamentaux   portée - contexte - function ms tech daysFondamentaux   portée - contexte - function ms tech days
Fondamentaux portée - contexte - function ms tech days
 
Function oop - bonnes pratiques ms tech days
Function   oop - bonnes pratiques ms tech daysFunction   oop - bonnes pratiques ms tech days
Function oop - bonnes pratiques ms tech days
 
Patterns et bonnes pratiques autour de JavaScript
Patterns et bonnes pratiques autour de JavaScriptPatterns et bonnes pratiques autour de JavaScript
Patterns et bonnes pratiques autour de JavaScript
 
Javascript ne se limite pas à jquery
Javascript ne se limite pas à jqueryJavascript ne se limite pas à jquery
Javascript ne se limite pas à jquery
 
JavaScript prise en main et fondamentaux
JavaScript prise en main et fondamentauxJavaScript prise en main et fondamentaux
JavaScript prise en main et fondamentaux
 
Présentation Javascript à l'ESI (Alger)
Présentation Javascript à l'ESI (Alger)Présentation Javascript à l'ESI (Alger)
Présentation Javascript à l'ESI (Alger)
 
Change mind about JS
Change mind about JSChange mind about JS
Change mind about JS
 
GWT : under the hood
GWT : under the hoodGWT : under the hood
GWT : under the hood
 
Présentation de ECMAScript 6
Présentation de ECMAScript 6Présentation de ECMAScript 6
Présentation de ECMAScript 6
 
Nouveautés JavaScript dans le monde Microsoft
Nouveautés JavaScript dans le monde MicrosoftNouveautés JavaScript dans le monde Microsoft
Nouveautés JavaScript dans le monde Microsoft
 
Cours JavaScript
Cours JavaScriptCours JavaScript
Cours JavaScript
 
Tp-jquery
Tp-jqueryTp-jquery
Tp-jquery
 
Quelle place pour le framework Rails dans le développement d'application web
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
 
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...
Fork / Join, Parallel Arrays, Lambdas : la programmation parallèle (trop ?) f...
 
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 ?
Javascript pour les développeurs Java : quels sont les pièges à éviter ?
 
Vert.x 3
Vert.x 3Vert.x 3
Vert.x 3
 
Javascript Json artchitecture
Javascript  Json artchitecture Javascript  Json artchitecture
Javascript Json artchitecture
 
Playing With PHP 5.3
Playing With PHP 5.3Playing With PHP 5.3
Playing With PHP 5.3
 
Meetup#1 talk#1
Meetup#1 talk#1Meetup#1 talk#1
Meetup#1 talk#1
 

Mehr von Jean-Pierre Vincent

Mesurer la performance : onload, pages
Mesurer la performance : onload, pagesMesurer la performance : onload, pages
Mesurer la performance : onload, pagesJean-Pierre Vincent
 
Les Performance de rendu sur mobile
Les Performance de rendu sur mobileLes Performance de rendu sur mobile
Les Performance de rendu sur mobileJean-Pierre Vincent
 
Performances web - quoi de neuf ?
Performances web - quoi de neuf ?Performances web - quoi de neuf ?
Performances web - quoi de neuf ?Jean-Pierre Vincent
 
Accélération des pages Web : les bases en exemple
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
 
Techniques accélération des pages web #kiwiparty
Techniques accélération des pages web #kiwipartyTechniques accélération des pages web #kiwiparty
Techniques accélération des pages web #kiwipartyJean-Pierre Vincent
 
Techniques d'accélération des pages web
Techniques d'accélération des pages webTechniques d'accélération des pages web
Techniques d'accélération des pages webJean-Pierre Vincent
 
Retours sur le concours Webperf 2010
Retours sur le concours Webperf 2010Retours sur le concours Webperf 2010
Retours sur le concours Webperf 2010Jean-Pierre Vincent
 
Télés connectées et développement Web
Télés connectées et développement WebTélés connectées et développement Web
Télés connectées et développement WebJean-Pierre Vincent
 
Inclure du Javascript de manière performante
Inclure du Javascript de manière performanteInclure du Javascript de manière performante
Inclure du Javascript de manière performanteJean-Pierre Vincent
 
HTML5 maintenant partie 3 : multimedia
HTML5 maintenant partie 3 : multimediaHTML5 maintenant partie 3 : multimedia
HTML5 maintenant partie 3 : multimediaJean-Pierre Vincent
 
HTML5 maintenant partie 2 : APIs
HTML5 maintenant partie 2 : APIsHTML5 maintenant partie 2 : APIs
HTML5 maintenant partie 2 : APIsJean-Pierre Vincent
 
HTML5 maintenant partie 1 : la sémantique
HTML5 maintenant partie 1 : la sémantiqueHTML5 maintenant partie 1 : la sémantique
HTML5 maintenant partie 1 : la sémantiqueJean-Pierre Vincent
 

Mehr von Jean-Pierre Vincent (17)

Mesurer la performance : onload, pages
Mesurer la performance : onload, pagesMesurer la performance : onload, pages
Mesurer la performance : onload, pages
 
Les Performance de rendu sur mobile
Les Performance de rendu sur mobileLes Performance de rendu sur mobile
Les Performance de rendu sur mobile
 
La performance sur mobile
La performance sur mobileLa performance sur mobile
La performance sur mobile
 
Performances web - quoi de neuf ?
Performances web - quoi de neuf ?Performances web - quoi de neuf ?
Performances web - quoi de neuf ?
 
Accélération des pages Web : les bases en exemple
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
 
Introduction à la webperf
Introduction à la webperfIntroduction à la webperf
Introduction à la webperf
 
Techniques accélération des pages web #kiwiparty
Techniques accélération des pages web #kiwipartyTechniques accélération des pages web #kiwiparty
Techniques accélération des pages web #kiwiparty
 
Techniques d'accélération des pages web
Techniques d'accélération des pages webTechniques d'accélération des pages web
Techniques d'accélération des pages web
 
Les performances Web mobile
Les performances Web mobileLes performances Web mobile
Les performances Web mobile
 
Retours sur le concours Webperf 2010
Retours sur le concours Webperf 2010Retours sur le concours Webperf 2010
Retours sur le concours Webperf 2010
 
Télés connectées et développement Web
Télés connectées et développement WebTélés connectées et développement Web
Télés connectées et développement Web
 
Html5 bonnes-pratiques
Html5 bonnes-pratiquesHtml5 bonnes-pratiques
Html5 bonnes-pratiques
 
Inclure du Javascript de manière performante
Inclure du Javascript de manière performanteInclure du Javascript de manière performante
Inclure du Javascript de manière performante
 
HTML5 maintenant partie 3 : multimedia
HTML5 maintenant partie 3 : multimediaHTML5 maintenant partie 3 : multimedia
HTML5 maintenant partie 3 : multimedia
 
HTML5 maintenant partie 2 : APIs
HTML5 maintenant partie 2 : APIsHTML5 maintenant partie 2 : APIs
HTML5 maintenant partie 2 : APIs
 
HTML5 maintenant partie 1 : la sémantique
HTML5 maintenant partie 1 : la sémantiqueHTML5 maintenant partie 1 : la sémantique
HTML5 maintenant partie 1 : la sémantique
 
Html5 now light
Html5 now lightHtml5 now light
Html5 now light
 

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
  • 3.
  • 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