Ce tutoriel article JavaScript fournit quelques concepts de base sur les modules et les espaces de noms dans le langage de programmation JavaScript Ce tutoriel JavaScript discute de ses objectifs d'utilisation, comment d?finir , d?clarer et de les utiliser dans nos Codes source JavaScript, Nos applications Web JavaScript Par ailleurs, cette JavaScript ?galement nous fournir de nombreux utiles biblioth?ques JavaScript, frameworks JavaScript ? manipuler, ma?triser les modules JavaScript et JavaScript namespaces mieux.
- Demo
- Agrandir
- Recharger
- New window
Gratuit iPage h�bergement Web pour la premi�re ann�e MOMENT
Si vous �tes toujours � la recherche d'un fournisseur d'h�bergement Web fiable avec des tarifs abordables, pourquoi vous ne prenez pas un peu de temps pour essayer iPage, seulement avec $1.89/month, inclus $500+ Cr�dits suppl�mentaires gratuites pour le paiement de 24 mois ($45)?
Plus de 1.000.000 de clients + existisng peuvent pas avoir tort, vraiment vous n'�tes pas aussi! Plus important encore, lorsque vous enregistrez l'h�bergement web � iPage gr�ce � notre lien, nous allons �tre heureux de renvoyer un plein remboursement. C'est g�nial! Vous devriez essayer iPage h�bergement web GRATUITEMENT maintenant! Et contactez-nous pour tout ce que vous devez savoir sur iPage.
JavaScript does not come with support for modules. This blog post examines patterns and APIs that provide such support. It is split into the following parts:
- Patterns for structuring modules.
- APIs for loading modules asynchronously.
- Related reading, background and sources.
1. Patterns for structuring modules
A module fulfills two purposes: First, it holds content, by mapping identifiers to values. Second, it provides a namespace for those identifiers, to prevent them from clashing with identifiers in other modules. In JavaScript, modules are implemented via objects.- Namespacing: A top-level module is put into a global variable. That variable is the namespace of the module content.
- Holding content: Each property of the module holds a value.
- Nesting modules: One achieves nesting by putting a module inside another one.
Filling a module with content
Approach 1: Object literal.var namespace = { func: function() { ... }, value: 123 };Approach 2: Assigning to properties.
var namespace = {}; namespace.func = function() { ... }; namespace.value = 123;Accessing the content in either approach:
namespace.func(); console.log(namespace.value + 44);Assessment:
- Object literal.
- Pro: Elegant syntax.
- Con: As a single, sometimes very long syntactic construct, it imposes constraints on its contents. One must maintain the opening brace before the content and the closing brace after the content. And one must remember to not add a comma after the last property value. This makes it harder to move content around.
- Assigning to properties.
- Con: Redundant repetitions of the namespace identifier.
The Module pattern: private data and initialization
In the module pattern, one uses an Immediately-Invoked Function Expression (IIFE, [1]) to attach an environment to the module data. The bindings inside that environment can be accessed from the module, but not from outside. Another advantage is that the IIFE gives you a place to perform initializations.var namespace = function() { // set up private data var arr = []; // not visible outside for(var i=0; i<4; i++) { arr.push(i); } return { // read-only access via getter get values() { return arr; } }; }(); console.log(namespace.values); // [0,1,2,3]Comments:
- Con: Harder to read and harder to figure out what is going on.
- Con: Harder to patch. Every now and then, you can reuse existing code by patching it just a little. Yes, this breaks encapsulation, but it can also be very useful for temporary solutions. The module pattern makes such patching impossible (which may be a feature, depending on your taste).
- Alternative for private data: use a naming convention for private properties, e.g. all properties whose names start with an underscore are private.
var namespace = {}; (function(ns) { // (set up private data here) ns.func = function() { ... }; ns.value = 123; }(namespace));Variation: this as the namespace identifier (cannot accidentally be assigned to).
var namespace = {}; (function() { // (set up private data here) this.func = function() { ... }; this.value = 123; }).call(namespace); // hand in implicit parameter "this"
Referring to sibling properties
Use this. Con: hidden if you nest functions (which includes methods in nested objects).var namespace = { _value: 123; // private via naming convention getValue: function() { return this._value; } anObject: { aMethod: function() { // "this" does not point to the module here } } }Global access. Cons: makes it harder to rename the namespace, verbose for nested namespaces.
var namespace = { _value: 123; // private via naming convention getValue: function() { return namespace._value; } }Custom identifier: The module pattern (see above) enables one to use a custom local identifier to refer to the current module.
- Module pattern with object literal: assign the object to a local variable before returning it.
- Module pattern with parameter: the parameter is the custom identifier.
Private data and initialization for properties
An IFEE can be used to attach private data and initialization code to an object. It can do the same for a single property.var ns = { getValue: function() { var arr = []; // not visible outside for(var i=0; i<4; i++) { arr.push(i); } return function() { // actual property value return arr; }; }() };Read on for an application of this pattern.
Types in object literals
Problem: A JavaScript type is defined in two steps. First, define the constructor. Second, set up the prototype of the constructor. These two steps cannot be performed in object literals. There are two solutions:- Use an inheritance API where constructor and prototype can be defined simultaneously [4].
- Wrap the two parts of the type in an IIFE:
var ns = { Type: function() { var constructor = function() { // ... }; constructor.prototype = { // ... }; return constructor; // value of Type }() };
Managing namespaces
Use the same namespace in several files: You can spread out a module definition across several files. Each file contributes features to the module. If you create the namespace variable as follows then the order in which the files are loaded does not matter. Note that this pattern does not work with object literals.var namespace = namespace || {};Nested namespaces: With multiple modules, one can avoid a proliferation of global names by creating a single global namespace and adding sub-modules to it. Further nesting is not advisable, because it adds complexity and is slower. You can use longer names if name clashes are an issue.
var topns = topns || {}; topns.module1 = { // content } topns.module2 = { // content }YUI2 uses the following pattern to create nested namespaces.
YAHOO.namespace("foo.bar"); YAHOO.foo.bar.doSomething = function() { ... };
2. APIs for loading modules asynchronously
Avoiding blocking: The content of a web page is processed sequentially. When a script tag is encountered that refers to a file, two steps happen:- The file is downloaded.
- The file is interpreted.
2.1. RequireJS
RequireJS has been created as a standard for modules that work both on servers and in browsers. The RequireJS website explains the relationship between RequireJS and the earlier CommonJS standard for server-side modules [3]:CommonJS defines a module format. Unfortunately, it was defined without giving browsers equal footing to other JavaScript environments. Because of that, there are CommonJS spec proposals for Transport formats and an asynchronous require.RequireJS projects have the following file structure:RequireJS tries to keep with the spirit of CommonJS, with using string names to refer to dependencies, and to avoid modules defining global objects, but still allow coding a module format that works well natively in the browser. RequireJS implements the Asynchronous Module Definition (formerly Transport/C) proposal.
If you have modules that are in the traditional CommonJS module format, then you can easily convert them to work with RequireJS.
project-directory/ project.html legacy.js scripts/ main.js require.js helper/ util.jsproject.html:
<!DOCTYPE html> <html> <head> <title>My Sample Project</title> <!-- data-main attribute tells require.js to load scripts/main.js after require.js loads. --> <script data-main="scripts/main" src="/javascript/article/Modules_and_Namespaces_in_JavaScript.php/scripts/require.js"></script> </head> <body> <h1>My Sample Project</h1> </body> </html>main.js: helper/util is resolved relative to data-main. legacy.js ends with .js and is assumed to not be in module format. The consequences are that its path is resolved relative to project.html and that there isn�t a function parameter to access its (module) contents.
require(["helper/util", "legacy.js"], function(util) { //This function is called when scripts/helper/util.js is loaded. require.ready(function() { //This function is called when the page is loaded //(the DOMContentLoaded event) and when all required //scripts are loaded. }); });Other features of RequireJS:
- Specify and use internationalization data.
- Load text files (e.g. to be used for HTML templating)
- Use JSONP service results for initial application setup.
2.2. YUI3
Version 3 of the YUI JavaScript framework brings its own module infrastructure. YUI3 modules are loaded asynchronously. The general pattern for using them is as follows.YUI().use('dd', 'anim', function(Y) { // Y.DD is available // Y.Anim is available });Steps:
- Provide IDs �dd� and �anim� of the modules you want to load.
- Provide a callback to be invoked once all modules have been loaded.
- The parameter Y of the callback is the YUI namespace. This namespace contains the sub-namespaces DD and Anim for the modules. As you can see, the ID of a module and its namespace are usually different.
YUI.add('mymodules-mod1', function(Y) { Y.namespace('mynamespace'); Y.mynamespace.Mod1 = function() { // expose an API }; }, '0.1.1' // module version );YUI includes a loader for retrieving modules from external files. It is configured via a parameter to the API. The following example loads two modules: The built-in YUI module dd and the external module yui_flot that is available online.
YUI({ modules: { yui2_yde_datasource: { // not used below fullpath: 'http://yui.yahooapis.com/datasource-min.js' }, yui_flot: { fullpath: 'http://bluesmoon.github.com/yui-flot/yui.flot.js' } } }).use('dd', 'yui_flot', function(Y) { // do stuff });
2.3. Script loaders
Similarly to RequireJS, script loaders are replacements for script tags that allow one to load JavaScript code asynchronously and in parallel. But they are usually simpler than RequireJS. Examples:- LABjs: a relatively simple script loader. Use it instead of RequireJS if you need to load scripts in a precise order and you don't need to manage module dependencies. Background: �LABjs & RequireJS: Loading JavaScript Resources the Fun Way� describes the differences between LABjs and RequireJS.
- yepnope: A fast script loader that allows you to make the loading of some scripts contingent on the capabilities of the web browser.
- Sent (0)
- Nouveau
Générez vos vidéos d'entreprise par l'IA avec la voix ou simplement du texte
chatGPTaz.com
Parlez à ChatGPT dans votre langue maternelle
AppAIVidéo
Votre première application vidéo AI GRATUITE
Deepfake Video
Deepfake AI Video Maker
Deepfake
Deepfake AI Video Maker
AI Deep Fake
Deepfake AI Video Maker
AIvidio
AI Video Mobile Solutions
AIvideos
AI Video Platform & Solutions
AIvedio
AI Video App Maker
Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT
Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT
Temu gratuit 500 $ pour les nouveaux utilisateurs
Claim Free Temu $500 Credit via Affiliate & Influencer Program
Crédits publicitaires TikTok gratuits
Maîtrisez les publicités TikTok pour le marketing de votre entreprise
Dall-E-OpenAI.com
Générez automatiquement des images créatives avec l'IA
chatGPT4.win
Parlez à ChatGPT dans votre langue maternelle
Premier produit d'intelligence artificielle d'Elon Musk - Grok/UN.com
Parlez au chatbot Grok AI dans votre langue
Outily.win
Centre d'outils ouvert et gratuit, utilisable par tous et pour tous, avec des centaines d'outils
GateIO.gomymobi.com
Airdrops gratuits à réclamer et à partager jusqu'à 150 000 $ par projet
iPhoneKer.com
Économisez jusqu'à 630 $ à l'achat d'un nouvel iPhone 16
Acheter le robot Tesla Optimus
Commandez votre robot Tesla Bot : Optimus Gen 2 dès aujourd'hui pour moins de 20 000 $
R�ponse
Nice tutorial!