Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Functions: Using Function As A Namespace

Thursday, December 16, 2021

JavaScript Functions: Using Function As A Namespace

JavaScript does not have a built-in feature to define a namespace.  A namespace is basically a container of your code that it does not pollute the other codes that's on page.  Namespace allows you to play nice with people's code and other JavaScript libraries.

Fortunately, JavaScript functions have their own contexts and scope.  Therefore, we can use functions as a namespace so that it does not pollute the global scope.

The easiest way to create a namespace on a page is to encapsulate everything in an anonymous function like the code below.


    <script>
        (function () {
            // put your code here
        }());

    </script>

Another way of using namespace is to assign the anonymous function to a variable


    <script>
       var myNameSpace = (function () {
            // put your code here
        }());

    </script>

3 comments:

  1. If you require help with an iPhone repair or a Samsung repair please feel free to connect with us at the link below. Teck Repair is an expert in screen repair services in Swindon UK
    https://teck.repair/samsung-galaxy-note-10-repair-swindon/

    ReplyDelete
  2. After Gradution Your guide to our exporters is the Online Career Counsellin in Delhi Fees export for your guides save future
    https://www.jitinchawla.com/blog/here-is-why-you-should-study-in-the-netherlands

    ReplyDelete
  3. Tapouts combine the power of search and social optimised by our unique (DNA) Digital Network Algorithms.
    As a Digital Marketing Company we can enable services to support your reputation management.

    We also provide premium support services required for your Digital Marketing Needs.

    ReplyDelete

Search This Blog