Home > Web Front-end > JS Tutorial > body text

Namespaces in JavaScript

韦小宝
Release: 2018-03-07 09:38:14
Original
1100 people have browsed it

Students who have studied PHP all know the concept of namespace. In a complex system, there will be many functions and objects, so many functions provided by the language and predefined by the architecture. and objects. Since programming standards require meaningful names, it is inevitable that incorrect calls will occur with the same name. But with namespaces, the trouble is gone. Not only can functions and objects be classified and organized, but also isolation can be formed to solve the problem of duplicate names.

Using JavaScript is not so comfortable. Javascript only has function scope. All blocks and files are considered to be a namespace. Sometimes errors caused by duplicate names are confusing and difficult to debug and solve.

A simple example

<input type="button" value="test" onclick="alert();"/>
        <script type="text/javascript">
            function alert(){
                //.......
                test2();
                //.......
            }
            function test2(){
                alert(&#39;test2&#39;)
            }
        </script>
Copy after login

In this example, different performances will occur in different browsers. IE will report Stack over flow, Firefox Will die. . . Anyway, it will report an error. It is a very simple error. An alert function is customized in the code. The test2 function is called in the alert function. The test2 function intends to call the alert method of the window. In this way, it is called in a loop. Maybe you will say it is so obvious after reading it. Who would make the mistake, but if the custom method is called close (this will often happen), and then an external file function is called internally, and the function calls the window's close method, the error will be hidden a lot.

Simple namespace

Since JavaScript does not have file scope, different functions are scattered in different files, or even by different people Writing, the probability of duplicate names is greatly increased. Is it enough to be careful enough? Not necessarily. There are also some unexpected situations. For example, inheritance is often used, so I wrote a function name extend that has never appeared before. Unexpectedly, the extend function was added to EcmaScript5, and the necessity of namespaces was reflected.

JavaScript has function scope. You can use this to write custom functions into a function body, so that the variables, objects, and functions in the function are isolated from the outside just like they are in a namespace.

<input type="button" value="test" onclick="(new namespace()).alert();"/>
        
        <script type="text/javascript">
            function namespace(){
                this.alert=function(){
                    console.log(&#39;test&#39;);
                }
            }
        </script>
Copy after login

In this way, the customized alert method will not conflict with the window alert.

Simple Evolution

This is possible, but there are problems. The biggest problem is that the calling method is complicated and ugly! The object must be instantiated every time it is called, and then its methods must be called. Simply modify the code to achieve automatic instantiation.

<input type="button" value="test" onclick="NS.alert();"/>
        <script type="text/javascript">
            (function namespace(){
                this.alert=function(){
                    console.log(&#39;test&#39;);
                }
                window.NS=this;
            })();
        </script>
Copy after login

To understand the above code, you first need to understand the technical structure of "immediate execution function" (that's what Jianghu people call it). The structure is similar to this

(function xxx(){
       //function body 
 })();
Copy after login

In this way, you can write the xxx function after the definition Then it will be executed automatically, which looks magical. In fact, the above writing can be broken down into this:

function xxx(){
       //function body 
 }
xxx();
Copy after login

is define a function, and then use bracket syntax to call it, and the layer of brackets outside the function definition only plays a role Convert function declarations into function definition expressions, since only expressions can be called using parentheses. After understanding these monsters, the above code is simple. At the end of the custom namespace function, assign this to the NS attribute of the window, and use NS.xx directly when calling. Looks a lot better.

Beautify it

The above writing method looks good, but the function name namespace seems to be redundant, you can beautify it

(function (){
                this.alert=function(){
                    console.log(&#39;test&#39;);
                }
                window.NS=this;
            })();
Copy after login

has become an anonymous function that is executed immediately, which is a bit beautified, but it still looks weird. Yes, it is obviously an instantiated function. Why is the method definition not written in the prototype? Well, how to write a prototype of an anonymous function. . . , you still have to use your brain

(function(){
                var _NS=function(){
                }
                _NS.prototype.alert=function(){
                    console.log(&#39;test&#39;);
                }
                window.NS=new _NS();
            })();
Copy after login

Write a few useful functions

querySelector and querySelectorAll are new query interfaces provided by W3C, but The name is so long, I wrote a simple one myself. The innerHTML attribute is also commonly used. I wrote a simple version of jQuery’s html method

(function () {
            var _NS = function () {
            }
            _NS.prototype.select = function (selector,context) {
                var context = context || document;
                return context.querySelectorAll(selector);
            }
            _NS.prototype.isArrayLike=function(obj){
                if(obj instanceof Array){
                    return true;
                }

                var length=obj.length;
                if ( obj.nodeType === 1 && length ) {
                    return true;
                }
                return false;
            }
            _NS.prototype.html = function (obj,value) {
                var isArray=this.isArrayLike(obj), i=0;
                if (typeof value == &#39;string&#39;) {
                    if (!isArray) {
                        obj.innerHTML = value;
                    } else {
                        var length = obj.length;
                        while (i < length) {
                            obj[i].innerHTML = value;
                            i += 1;
                        }
                    }
                } else {
                    if (!isArray) {
                        return obj.innerHTML;
                    } else {
                        return obj[0].innerHTML;
                    }
                }
            }
            window.NS = new _NS();
        })();
Copy after login

The namespace effectively prevents conflicts between function names/class names and others. When using multiple When there is a conflict with a third-party framework or class library, the only thing you can do is to abandon one of them.
It is inevitable to come into contact with JavaScript when engaging in web development. The latest version of JavaScript still does not support namespaces, so the problem of naming conflicts is undoubtedly prominent. Imagine that you referenced two js files, but found that you had to Giving up one of them and writing a lot of extra code is undoubtedly very frustrating. Before the new version of JavaScript introduces the concept of namespaces, it is the basic obligation of us programmers to carry forward the spirit of self-reliance and creativity;

Related articles:

Detailed usage of PHP namespace

JS namespace writing example code


The above is the detailed content of Namespaces in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!