Using global namespace & this keyword



Avoiding using the global namespace

The global namespace is where all the native JavaScript libraries live. The global namespace includes nested namespaces, such as Math, WebSocket, and JSON.

The global namespace is available to all code within an application session. With the increasing number of third-party libraries in use, the potential for naming conflicts increases.

Defining a namespace with the same name, the JavaScript runtime can’t identify which namespace they intended to use. This is why keeping your objects out of the global namespace is important.

One strategy to avoid name collisions is to create your own namespaces for your JavaScript libraries. The following code demoatrates this:

<head>
<title></title>
<style type="text/css">
    #div1 {
        width: 450px;
        height: 150px;
        border: 1px solid green;
    }
</style>
</head>
<body>
    <div id="div1">  </div>
    <input type="submit" onclick="globalNamespace()" value="Global Namespace" />
<script type="text/javascript">
  var globalNamespace = function () {
    var com = {};
    com.Bookstore = {};
    com.Bookstore.Book = {
        Exam: '70 480',
        title: 'Programming in HTML5, CSS3 & JavaScript'
    };
    com.Bookstore.Author = {
        site: 'infocodify.com',
        platform: 'MVC6'
    }
    document.getElementById("div1").innerHTML =
        (("Exam : " + com.Bookstore.Book.Exam + "<br>" + 
        "\nTitle : " + com.Bookstore.Book.title) + "<br>" +
        ("\nSite : " + com.Bookstore.Author.site + "<br>" + 
        "\nPlatform : " + com.Bookstore.Author.platform));
  }
</script>
</body>

Creating the objects in this way, you can be reasonably certain that if another developer creates a useful library to manage books that you want to include in your site, you won’t have to worry about a naming collision

Leveraging the this keyword

The keyword this is a special term that allows JavaScript developers to reference the containing object directly.

The following code snippet demonstrates the context of the this keyword:

<head>
<title></title>
<style>
    div {
        width: 400px;
        height: 100px;
        border: 1px solid black;
    }
</style>
</head>
<body>
    <div id="div1">  </div>
    <input type="submit" onclick="thisKeyword()" value="THIS KEYWORD" />
<script type="text/javascript">
    var thisKeyword = function () {
        var exam = {
            name: "Exam 70-480 Programming in HTML5, CSS3 &JavaScript",
            getBrand: function () {
                var a = function () {
                    document.getElementById("div1").innerHTML = (this.name);
                }.bind(this);
                return a();
            }
        };
        exam.getBrand();
    }
</script>
</body>

PROMOTIONS