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
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