Home > Web Front-end > JS Tutorial > JS modular usage instructions for back-end programmers

JS modular usage instructions for back-end programmers

php中世界最好的语言
Release: 2018-06-04 10:48:55
Original
1306 people have browsed it

This time I will bring you the instructions for using JS modularization for back-end programmers. What are the precautions for back-end programmers to use JS modularization. Here are practical cases, let’s take a look.

Basic Mode

Anonymous Closure

Anonymous closure is a very common code isolation method, which declares anonymous objects and executes them immediately. The variables and methods declared in the anonymous function and the anonymous function itself will not pollute the function outside the body. At the same time, the call of the anonymous function forms a closure, so that the function body can use the function declared outside the body. Variables and methods.

(function () {    // ... all vars and functions are in this scope only
    // still maintains access to all globals}());
Copy after login

Global import

We know thatJavaScript GlobalThe scope of variablesruns through the whole world, and global variables can also be used or even declared within functions, so It can easily lead to code clutter that is difficult to manage.
Global import mode is a variant of anonymous closure. It adds parameters to import global variables and agrees that external modules can only be accessed through imported parameters inside the anonymous function, thus making the dependencies between modules clear and easy to manage.

(function ($, YAHOO) { // now have access to globals jQuery (as $) and YAHOO in this code}(jQuery, YAHOO));

This convention cannot be enforced To prevent access to global variables within the function body, one solution is to treat all modules in this way and only export the module itself to global variables, which can greatly reduce the use of global variables.

Module export

Module export is to return the result of the immediate execution of the anonymous function and assign it to a global variable. Anonymous functions only return open objects, and their internally defined variables and functions are still invisible to the outside world.

var MODULE = (function () {    var my = {},
        privateVariable = 1;    function privateMethod() {        // ...
    }
    my.moduleProperty = 1;
    my.moduleMethod = function () {        // ...
    };    return my;
}());
Copy after login

Advanced mode

Expansion mode

JavaScript objects support hot expansion. Combined with the global import mode, we can expand the module.

var MODULE = (function (my) {
    my.anotherMethod = function () {        // added method...
    };    return my;
}(MODULE));
Copy after login

This mode assumes that the MODULE has been declared. If it is not declared, an error will occur.

Wide expansion mode

Wide expansion mode uses a trick to call an anonymous function and pass MODULE || {} as a parameter to solve the problem of calling error if MODULE is not declared in advance. This mode also hides a wonderful thing, that is, multiple expansion modes can be called in parallel without being blocked.

var MODULE = (function (my) {    // add capabilities...
    return my;
}(MODULE || {}));
Copy after login

Tight expansion mode

Wide expansion mode is great, but one drawback is that it cannot safely handle overloading of method attributes. The tight extension mode keeps references to old methods and can flexibly reuse the functions of old methods in new methods defined.

var MODULE = (function (my) {    var old_moduleMethod = my.moduleMethod;
    my.moduleMethod = function () {        // method override, has access to old through old_moduleMethod...
    };    return my;
}(MODULE));
Copy after login

Cloning and Inheritance

var MODULE_TWO = (function (old) {    var my = {},
        key;    for (key in old) {        if (old.hasOwnProperty(key)) {
            my[key] = old[key];
        }
    }    var super_moduleMethod = old.moduleMethod;
    my.moduleMethod = function () {        // override method on the clone, access to super through super_moduleMethod
    };    return my;
}(MODULE));
Copy after login

The cloning and inheritance modes are almost the module reuse methods that have the least impact on the original modules. This mode is reused by cloning the old module attributes and can be combined with The tight expansion mode handles the problem of method overloading. It should be noted that this is a kind of shallow cloning. When the attribute of the old module is an object, modifications to this object will affect each other between the old and new modules.

Cross-file private state

When a module is split into multiple files, you will find a limitation when using wide expansion mode. The methods in each file will maintain their own private state and cannot be used in the module. Shared in multiple files, the following example shows how to share private state in the same module in this case.

var MODULE = (function (my) {    var _private = my._private = my._private || {},
        _seal = my._seal = my._seal || function () {            delete my._private;            delete my._seal;            delete my._unseal;
        },
        _unseal = my._unseal = my._unseal || function () {
            my._private = _private;
            my._seal = _seal;
            my._unseal = _unseal;
        };    // permanent access to _private, _seal, and _unseal
    return my;
}(MODULE || {}));
Copy after login

Each file maintains a local variable _private for sharing with other modules. After the module is loaded, call MODULE._seal to destroy the external access attribute of the local variable _private. If the module needs to be expanded, call _unseal before loading the file to output the local variable _private to the externally accessible attributes. After loading, call _seal to destroy the externally accessed attributes.

Submodule

Submodule defines the attributes of the module as a module, and can flexibly use the various modes mentioned above.

MODULE.sub = (function () {    var my = {};    // ...
    return my;
}());
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Use JS to perform encryption and decryption operations

How to use JS to make reference transfer and value transfer

The above is the detailed content of JS modular usage instructions for back-end programmers. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template