Namespaces in JavaScript. Putting an end to the question

The development of the javascript language transfers the execution of codes to a distributed network of users and takes the load off the server. This is a smart approach. The introduction of the keywords class, extends and static into js made it easy to model the project domain with classes and objects. It is wonderful. The next issue that needs to be considered as the complexity of a js project grows is the namespace. It is it that allows you to avoid conflicts with a heap of heterogeneous js scripts. As practice shows, for some reason, great difficulties arose with this issue. See links below:

https://stackoverflow.com/questions/881515/how-do-i-declare-a-namespace-in-javascript

https://habr.com/ru/post/527610/

https://habr.com/ru/post/31596/

https://habr.com/ru/post/527610/

https://habr.com/ru/post/528218/

Badly. Very difficult decisions. The following article brings some clarity to the question:

https://drbrain.ru/articles/js-namespaces/

But even in it the thought is not brought to its logical end. However, by slightly modifying this article, you can get a very simple scheme (pattern) for working with the namespace:

/* namespaceOne */{

    class First {
        //статическое свойство
        static className = "First";
        constructor() {
            console.log("class First consructed");
        }

        print() {
            console.log("First print");
        }

        //статическая функция
        static printStatic() {
            console.log(First.className + " static print ");
        }
    }

    //наследование
    class Second extends First {
        constructor() {
            super();
            Second.className = "Second";
            console.log("class Second consructed");
        }
        //полиморфизм
        print() {
            console.log(Second.className + " print");
        }
    }

    class Third {
        className;
        encapsulation;
        constructor() {
            this.className = "Third";
            this.encapsulation = new Second(); //инкапсуляция
            console.log("class Third consructed");
        }
        print() {
            console.log("Third print");
        }
    }

    //экспорт пространства имен
    var namespaceOne = {First: First, Second: Second, Third: Third};
}


/* namespaceTwo */{
    //импорт пространства имен
    namespaceOne.First.printStatic();
    let second = new namespaceOne.Second();
    second.print();

    let ThirdClass = namespaceOne.Third;
    let third = new ThirdClass();
    third.print();
}

There is a feeling that the import, export keywords will be just syntactic sugar for such a scheme. Now you can safely add your code to any project by simply putting it in {in curly braces}. With a high probability, you will not have conflicts.

Similar Posts

Leave a Reply