SlideShare une entreprise Scribd logo
1  sur  17
Télécharger pour lire hors ligne
an nymes
Les fonctions
Sylvain Zyssman
@sylzys sylzys
CaenJS - 14/09/2013
Good or Evil ?
lundi 16 septembre 13
lundi 16 septembre 13
1 function hello() {
2 !alert('world');
3 }
4
5 hello();
1 var anon = fonction() {
2 !alert ('hello anonymous');
3 }
4 anon();
Fonction nommee
Fonction anonyme
lundi 16 septembre 13
Ou encore
1 setTimeout(function() {
2 alert('Vive CaenJS');
3 }, 1000);
1 $('.buzz').click(function(){
2 !console.log(" To infinity and beyond ");
3 });
lundi 16 septembre 13
Rien a declarer ?
1 var add = new Function("x", "y", "return x + y;");
Function constructor
1 function add(x, y) {
2 return x + y;
3 }
Function declaration
Function expression
1 var add = function(x, y) {
2 return x + y;
3 };
lundi 16 septembre 13
Runtime
VS
Parsetime
1 plop(); // alerte plop!
2 function plop() {
3 alert('plop!');
4 }
1 plop();
2 var plop = function()
3 {
4 !alert('plop!'); //erreur
5 };
lundi 16 septembre 13
Une affaire de scope
1 var i = 100;
2 (function (){
3 for(var i=0; i<10; i++) {
4 console.log(i); // 0...9
5 }
6 }());
7 console.log(i); //100
Attention au hoisting
1 var x = 3;
2 (function (){
3 console.log(x + 2); //NaN - x is not
4 defined
5 var x = 0; //var declaration
6 }());
}
Scope
fonctionnel {
1 function foo() {
2 ! var x = 1;
3 ! if (x) {
4 ! ! (function () {
5 ! ! ! var x = 2;
6 ! ! ! console.log(x); //2
7 ! ! }());
8 ! }
9 ! console.log(x);//1.
10 }
lundi 16 septembre 13
Des avantages ...
lundi 16 septembre 13
• Optimiser le Garbage Collector
• Creer un scope temporaire / prive
• Garder un code bref
lundi 16 septembre 13
Alors pourquoi nommer
ses fonctions ?
lundi 16 septembre 13
Rendre le code
plus lisible
Limiter les niveaux
d’imbrication
1 fs.readdir(source, function(err, files) {
2 if (err) {
3 console.log('Error finding files: ' + err);
4 } else {
5 files.forEach(function(filename, fileIndex) {
6 console.log(filename);
7 gm(source + filename).size(function(err,
8 values) {
9 if (err) {
10 console.log('Error identifying file
11 size: ' + err);
12 } else {
13 console.log(filename + ' : ' + values);
14 aspect = (values.width / values.height);
15 widths.forEach(function(width,
16 widthIndex) {
17 height = Math.round(width / aspect);
18 console.log('resizing ' + filename +
19 'to ' + height + 'x' +
20 height);
21 this.resize(width, height).write(
22 destination + 'w' + width
23 + '_' + filename,
24 function(err) {
25 if (err) console.log('Error writing
26 file: ' + err);
27 });
28 }.bind(this));
29 }
30 });
31 });
32 }
33 }); • source: http://callbackhell.com/
EVIL
lundi 16 septembre 13
Tracer, debugguer
1 function foo(){
2 return bar();
3 }
4 function bar(){
5 return baz();
6 }
7 function baz(){
8 debugger;
9 }
10 foo();
1 baz()
2 bar()
3 foo()
4 main.js()
1 function foo(){
2 return bar();
3 }
4 var bar = (function(){
5 if (window.addEventListener) {
6 return function(){
7 return baz();
8 };
9 }
10 else if (window.attachEvent) {
11 return function() {
12 return baz();
13 };
14 }
15 })();
16 function baz(){
17 debugger;
18 }
19 foo();
1 baz()
2 (?)()
3 foo()
4 main.js()
Code
Stack
source: http://kangax.github.io/nfe/
lundi 16 septembre 13
Utiliser la recursivite
Access to arguments.caller and arguments.callee now throw an exception.
Thus any anonymous functions that you want to reference will need to be named, like so:
1 setTimeout(function later(){
2 // do stuff...
3 setTimeout( later, 1000 );
4 }, 1000 );
5
• nom de la fonction
• argument.callee
• variable in-scope
ECMAScript 5 - strict mode
lundi 16 septembre 13
Performance ?
http://jsperf.com/immediate-vs-named
lundi 16 septembre 13
http://www.empowernetwork.com
lundi 16 septembre 13
Quelques liens utiles
• https://developer.mozilla.org/en-US/docs/Web/JavaScript/
Reference
• http://callbackhell.com/
• http://kangax.github.io/nfe/
• http://ejohn.org/category/blog/ (auteur de ‘Secrets of the JS
Ninja’)
• http://javascriptweblog.wordpress.com/
lundi 16 septembre 13
Merci !
Des questions ?
lundi 16 septembre 13

Contenu connexe

Tendances

Enib cours c.a.i. web - séance #5 - groovy
Enib   cours c.a.i. web - séance #5 - groovyEnib   cours c.a.i. web - séance #5 - groovy
Enib cours c.a.i. web - séance #5 - groovy
Horacio Gonzalez
 
ENIB 2013-2014 - CAI Web #3: Groovy
ENIB 2013-2014 - CAI Web #3: GroovyENIB 2013-2014 - CAI Web #3: Groovy
ENIB 2013-2014 - CAI Web #3: Groovy
Horacio Gonzalez
 
Javascript - Fonctions : que fait ce code ?
Javascript - Fonctions : que fait ce code ?Javascript - Fonctions : que fait ce code ?
Javascript - Fonctions : que fait ce code ?
Ruau Mickael
 
Javascript - Tableaux : que fait ce code ?
Javascript - Tableaux : que fait ce code ?Javascript - Tableaux : que fait ce code ?
Javascript - Tableaux : que fait ce code ?
Ruau Mickael
 

Tendances (18)

Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)
Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)
Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)
 
09 big data mapreduce
09 big data mapreduce09 big data mapreduce
09 big data mapreduce
 
Compteur de visites
Compteur de visitesCompteur de visites
Compteur de visites
 
Enib cours c.a.i. web - séance #5 - groovy
Enib   cours c.a.i. web - séance #5 - groovyEnib   cours c.a.i. web - séance #5 - groovy
Enib cours c.a.i. web - séance #5 - groovy
 
PostgreSQL Meetup Nantes #2
PostgreSQL Meetup Nantes #2PostgreSQL Meetup Nantes #2
PostgreSQL Meetup Nantes #2
 
02 1 프로그램 작성 과정
02 1 프로그램 작성 과정02 1 프로그램 작성 과정
02 1 프로그램 작성 과정
 
Tour C++
Tour C++Tour C++
Tour C++
 
[Paris Unity3D meetup] - Système d’instancing dans endless legend reskin
[Paris Unity3D meetup] - Système d’instancing dans endless legend reskin[Paris Unity3D meetup] - Système d’instancing dans endless legend reskin
[Paris Unity3D meetup] - Système d’instancing dans endless legend reskin
 
Luigi Paris.py meetup presentation
Luigi Paris.py meetup presentationLuigi Paris.py meetup presentation
Luigi Paris.py meetup presentation
 
20080610 04 - Explorations visuelles de programmes
20080610 04 - Explorations visuelles de programmes20080610 04 - Explorations visuelles de programmes
20080610 04 - Explorations visuelles de programmes
 
Javascript #4.2 : fonctions for pgm
Javascript #4.2 : fonctions for pgmJavascript #4.2 : fonctions for pgm
Javascript #4.2 : fonctions for pgm
 
Python profiling
Python profilingPython profiling
Python profiling
 
ENIB 2013-2014 - CAI Web #3: Groovy
ENIB 2013-2014 - CAI Web #3: GroovyENIB 2013-2014 - CAI Web #3: Groovy
ENIB 2013-2014 - CAI Web #3: Groovy
 
Javascript - Fonctions : que fait ce code ?
Javascript - Fonctions : que fait ce code ?Javascript - Fonctions : que fait ce code ?
Javascript - Fonctions : que fait ce code ?
 
Analyse de données JSON dans Openrefine
Analyse de données JSON dans OpenrefineAnalyse de données JSON dans Openrefine
Analyse de données JSON dans Openrefine
 
Javascript - Tableaux : que fait ce code ?
Javascript - Tableaux : que fait ce code ?Javascript - Tableaux : que fait ce code ?
Javascript - Tableaux : que fait ce code ?
 
TP3: Comportement Temps Réel de l'Agent Perception
TP3: Comportement Temps Réel de l'Agent PerceptionTP3: Comportement Temps Réel de l'Agent Perception
TP3: Comportement Temps Réel de l'Agent Perception
 
Ruby STAR
Ruby STARRuby STAR
Ruby STAR
 

En vedette

Web security
Web securityWeb security
Web security
Layla Tk
 
Ddоs практическое руководство к выживанию А.Лямин
Ddоs практическое руководство к выживанию А.ЛяминDdоs практическое руководство к выживанию А.Лямин
Ddоs практическое руководство к выживанию А.Лямин
HighLoad Lab.
 
The world's 10 great societies 世界十大偉大社會 (非清晰版)(開音箱)
The world's 10 great societies 世界十大偉大社會 (非清晰版)(開音箱)The world's 10 great societies 世界十大偉大社會 (非清晰版)(開音箱)
The world's 10 great societies 世界十大偉大社會 (非清晰版)(開音箱)
Yu-Chia Hsu
 
аллея доблести и славы редуктор
аллея доблести и славы редуктораллея доблести и славы редуктор
аллея доблести и славы редуктор
Say2rus
 
บทที่5การสร้างฟอร์ม
บทที่5การสร้างฟอร์มบทที่5การสร้างฟอร์ม
บทที่5การสร้างฟอร์ม
niwat50
 

En vedette (20)

01
0101
01
 
Web security
Web securityWeb security
Web security
 
Ddоs практическое руководство к выживанию А.Лямин
Ddоs практическое руководство к выживанию А.ЛяминDdоs практическое руководство к выживанию А.Лямин
Ddоs практическое руководство к выживанию А.Лямин
 
The world's 10 great societies 世界十大偉大社會 (非清晰版)(開音箱)
The world's 10 great societies 世界十大偉大社會 (非清晰版)(開音箱)The world's 10 great societies 世界十大偉大社會 (非清晰版)(開音箱)
The world's 10 great societies 世界十大偉大社會 (非清晰版)(開音箱)
 
Alternative Sources of Funding | LEDC
Alternative Sources of Funding | LEDCAlternative Sources of Funding | LEDC
Alternative Sources of Funding | LEDC
 
WDCEP's 2013 Annual Meeting & Development Showcase Sponsorship Kit
WDCEP's 2013 Annual Meeting & Development Showcase Sponsorship KitWDCEP's 2013 Annual Meeting & Development Showcase Sponsorship Kit
WDCEP's 2013 Annual Meeting & Development Showcase Sponsorship Kit
 
Стратегия развития направлений отдела комплектования
Стратегия развития направлений отдела комплектованияСтратегия развития направлений отдела комплектования
Стратегия развития направлений отдела комплектования
 
ABRA | Registration & Licensing
ABRA | Registration & LicensingABRA | Registration & Licensing
ABRA | Registration & Licensing
 
Business Financing | Business Finance Group | Doing Business 2.0
Business Financing | Business Finance Group | Doing Business 2.0Business Financing | Business Finance Group | Doing Business 2.0
Business Financing | Business Finance Group | Doing Business 2.0
 
Revenue Bonds | DMPED | Entrepreneur Road Map
Revenue Bonds | DMPED | Entrepreneur Road MapRevenue Bonds | DMPED | Entrepreneur Road Map
Revenue Bonds | DMPED | Entrepreneur Road Map
 
аллея доблести и славы редуктор
аллея доблести и славы редуктораллея доблести и славы редуктор
аллея доблести и славы редуктор
 
Top 5 PC Game Mods
Top 5 PC Game ModsTop 5 PC Game Mods
Top 5 PC Game Mods
 
Welcome to
Welcome toWelcome to
Welcome to
 
บทที่5การสร้างฟอร์ม
บทที่5การสร้างฟอร์มบทที่5การสร้างฟอร์ม
บทที่5การสร้างฟอร์ม
 
DC Development Report Sponsorship Kit
DC Development Report Sponsorship KitDC Development Report Sponsorship Kit
DC Development Report Sponsorship Kit
 
1010515
10105151010515
1010515
 
Csima ppt new
Csima ppt newCsima ppt new
Csima ppt new
 
Starting a Franchise | UPS | Doing Business 2.0
Starting a Franchise | UPS | Doing Business 2.0Starting a Franchise | UPS | Doing Business 2.0
Starting a Franchise | UPS | Doing Business 2.0
 
Georgia Avenue Retail/Restaurant Tour 2013
Georgia Avenue Retail/Restaurant Tour 2013Georgia Avenue Retail/Restaurant Tour 2013
Georgia Avenue Retail/Restaurant Tour 2013
 
WDCEP's 2014 Annual Meeting & Development Showcase Sponsorship Kit
WDCEP's 2014 Annual Meeting & Development Showcase Sponsorship KitWDCEP's 2014 Annual Meeting & Development Showcase Sponsorship Kit
WDCEP's 2014 Annual Meeting & Development Showcase Sponsorship Kit
 

Similaire à Good or Evil: les fonctions anonymes en Javascript

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
Jean-Pierre Vincent
 
jQuery — fonctionnalités avancées
jQuery — fonctionnalités avancéesjQuery — fonctionnalités avancées
jQuery — fonctionnalités avancées
Rémi Prévost
 

Similaire à Good or Evil: les fonctions anonymes en Javascript (19)

Javascript : fondamentaux et OOP
Javascript : fondamentaux et OOPJavascript : fondamentaux et OOP
Javascript : fondamentaux et OOP
 
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
 
jeu de serpent (Snake)
jeu de serpent (Snake)jeu de serpent (Snake)
jeu de serpent (Snake)
 
Cours javascript v1
Cours javascript v1Cours javascript v1
Cours javascript v1
 
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
 
Algo poo ts
Algo poo tsAlgo poo ts
Algo poo ts
 
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
 
Meet up symfony 11 octobre 2016 - Les formulaire
Meet up symfony 11 octobre 2016 - Les formulaireMeet up symfony 11 octobre 2016 - Les formulaire
Meet up symfony 11 octobre 2016 - Les formulaire
 
JavaScript prise en main et fondamentaux
JavaScript prise en main et fondamentauxJavaScript prise en main et fondamentaux
JavaScript prise en main et fondamentaux
 
Compte rendu jess
Compte rendu jessCompte rendu jess
Compte rendu jess
 
jQuery — fonctionnalités avancées
jQuery — fonctionnalités avancéesjQuery — fonctionnalités avancées
jQuery — fonctionnalités avancées
 
Future of java script web version
Future of java script web versionFuture of java script web version
Future of java script web version
 
Solution Linux 2009 - JavaScript
Solution Linux 2009 - JavaScriptSolution Linux 2009 - JavaScript
Solution Linux 2009 - JavaScript
 
Découverte du moteur de rendu du projet Spartan
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 Spartan
 
Rapport tp RSA
Rapport  tp  RSARapport  tp  RSA
Rapport tp RSA
 
Librairies Java qui changent la vie
Librairies Java qui changent la vieLibrairies Java qui changent la vie
Librairies Java qui changent la vie
 
SdE 2 - Langage C, Allocation de memoire
SdE 2 - Langage C, Allocation de memoireSdE 2 - Langage C, Allocation de memoire
SdE 2 - Langage C, Allocation de memoire
 

Good or Evil: les fonctions anonymes en Javascript

  • 1. an nymes Les fonctions Sylvain Zyssman @sylzys sylzys CaenJS - 14/09/2013 Good or Evil ? lundi 16 septembre 13
  • 3. 1 function hello() { 2 !alert('world'); 3 } 4 5 hello(); 1 var anon = fonction() { 2 !alert ('hello anonymous'); 3 } 4 anon(); Fonction nommee Fonction anonyme lundi 16 septembre 13
  • 4. Ou encore 1 setTimeout(function() { 2 alert('Vive CaenJS'); 3 }, 1000); 1 $('.buzz').click(function(){ 2 !console.log(" To infinity and beyond "); 3 }); lundi 16 septembre 13
  • 5. Rien a declarer ? 1 var add = new Function("x", "y", "return x + y;"); Function constructor 1 function add(x, y) { 2 return x + y; 3 } Function declaration Function expression 1 var add = function(x, y) { 2 return x + y; 3 }; lundi 16 septembre 13
  • 6. Runtime VS Parsetime 1 plop(); // alerte plop! 2 function plop() { 3 alert('plop!'); 4 } 1 plop(); 2 var plop = function() 3 { 4 !alert('plop!'); //erreur 5 }; lundi 16 septembre 13
  • 7. Une affaire de scope 1 var i = 100; 2 (function (){ 3 for(var i=0; i<10; i++) { 4 console.log(i); // 0...9 5 } 6 }()); 7 console.log(i); //100 Attention au hoisting 1 var x = 3; 2 (function (){ 3 console.log(x + 2); //NaN - x is not 4 defined 5 var x = 0; //var declaration 6 }()); } Scope fonctionnel { 1 function foo() { 2 ! var x = 1; 3 ! if (x) { 4 ! ! (function () { 5 ! ! ! var x = 2; 6 ! ! ! console.log(x); //2 7 ! ! }()); 8 ! } 9 ! console.log(x);//1. 10 } lundi 16 septembre 13
  • 8. Des avantages ... lundi 16 septembre 13
  • 9. • Optimiser le Garbage Collector • Creer un scope temporaire / prive • Garder un code bref lundi 16 septembre 13
  • 10. Alors pourquoi nommer ses fonctions ? lundi 16 septembre 13
  • 11. Rendre le code plus lisible Limiter les niveaux d’imbrication 1 fs.readdir(source, function(err, files) { 2 if (err) { 3 console.log('Error finding files: ' + err); 4 } else { 5 files.forEach(function(filename, fileIndex) { 6 console.log(filename); 7 gm(source + filename).size(function(err, 8 values) { 9 if (err) { 10 console.log('Error identifying file 11 size: ' + err); 12 } else { 13 console.log(filename + ' : ' + values); 14 aspect = (values.width / values.height); 15 widths.forEach(function(width, 16 widthIndex) { 17 height = Math.round(width / aspect); 18 console.log('resizing ' + filename + 19 'to ' + height + 'x' + 20 height); 21 this.resize(width, height).write( 22 destination + 'w' + width 23 + '_' + filename, 24 function(err) { 25 if (err) console.log('Error writing 26 file: ' + err); 27 }); 28 }.bind(this)); 29 } 30 }); 31 }); 32 } 33 }); • source: http://callbackhell.com/ EVIL lundi 16 septembre 13
  • 12. Tracer, debugguer 1 function foo(){ 2 return bar(); 3 } 4 function bar(){ 5 return baz(); 6 } 7 function baz(){ 8 debugger; 9 } 10 foo(); 1 baz() 2 bar() 3 foo() 4 main.js() 1 function foo(){ 2 return bar(); 3 } 4 var bar = (function(){ 5 if (window.addEventListener) { 6 return function(){ 7 return baz(); 8 }; 9 } 10 else if (window.attachEvent) { 11 return function() { 12 return baz(); 13 }; 14 } 15 })(); 16 function baz(){ 17 debugger; 18 } 19 foo(); 1 baz() 2 (?)() 3 foo() 4 main.js() Code Stack source: http://kangax.github.io/nfe/ lundi 16 septembre 13
  • 13. Utiliser la recursivite Access to arguments.caller and arguments.callee now throw an exception. Thus any anonymous functions that you want to reference will need to be named, like so: 1 setTimeout(function later(){ 2 // do stuff... 3 setTimeout( later, 1000 ); 4 }, 1000 ); 5 • nom de la fonction • argument.callee • variable in-scope ECMAScript 5 - strict mode lundi 16 septembre 13
  • 16. Quelques liens utiles • https://developer.mozilla.org/en-US/docs/Web/JavaScript/ Reference • http://callbackhell.com/ • http://kangax.github.io/nfe/ • http://ejohn.org/category/blog/ (auteur de ‘Secrets of the JS Ninja’) • http://javascriptweblog.wordpress.com/ lundi 16 septembre 13
  • 17. Merci ! Des questions ? lundi 16 septembre 13