Plusieurs sources pour cet article (car plusieurs techniques; à vous de choisir):
- Avec le module pattern: How to avoid global variables in JavaScript?
- Avec le Revealing module pattern
- Avec
window['varName'] = varName;
: How to avoid global variables in JavaScript? - Un peu de culture générale sur les différentes façons de déclarer des variables en Javascript: Difference between variable declaration syntaxes in Javascript (including global variables)?
Avec le module pattern:
Je détaille celui-ci car il me plait bien 🙂 Mais voir également le Revealing module pattern juste en-dessous qui apporte quelques améliorations.
- Variables et les fonctions privées: déclarées au sein d’une closure mais EN-DEHORS du scope du
return
- Variables et les fonctions publiques: déclarées au sein d’une closure mais DANS le scope du
return
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
YAHOO.myProject.myModule = function () { //"private" variables: var myPrivateVar = "I can be accessed only from within YAHOO.myProject.myModule."; //"private" method: var myPrivateMethod = function () { YAHOO.log("I can be accessed only from within YAHOO.myProject.myModule"); } return { myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty." myPublicMethod: function () { YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod."); //Within myProject, I can access "private" vars and methods: YAHOO.log(myPrivateVar); YAHOO.log(myPrivateMethod()); //The native scope of myPublicMethod is myProject; we can //access public members using "this": YAHOO.log(this.myPublicProperty); } }; }(); // the parens here cause the anonymous function to execute and return |
Avec le Revealing module pattern
Avec le Revealing module pattern, toutes les variables et toutes les fonctions sont d’abord déclarées en privé et on se sert du return
pour lister celles qu’on rend ensuite publiques. C’est plus lisible et plus pratique à l’utilisation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
var myModule = (function() { 'use strict'; var _privateProperty = 'Hello World'; var publicProperty = 'I am a public property'; function _privateMethod() { console.log(_privateProperty); } function publicMethod() { _privateMethod(); } return { publicMethod: publicMethod, publicProperty: publicProperty }; })(); myModule.publicMethod(); // outputs 'Hello World' console.log(myModule.publicProperty); // outputs 'I am a public property' console.log(myModule._privateProperty); // is undefined protected by the module closure myModule._privateMethod(); // is TypeError protected by the module closure |