Tech Junkie Blog: JavaScript Basics: Global Objects

Tuesday, March 28, 2017

JavaScript Basics: Global Objects

When the browser window opens and navigates to a webpage with your JavaScript code. A global object is created for your JavaScript program.

If you type the following line as the first line of code in your JavaScript file

var globalObj = this;

What do you think will get?  In this case you are referencing the Window object, which is JavaScript's object for the browser window.  As you can see there's a whole bunch of global properties and methods already defined at the global level.












However you don't have to be at the global level to access the Window object because the Window object has a special self referencing keyword called window. For example you can get a reference to the Window object inside a function wrapped inside an anonymous function with the window keyword.

(function () {

    console.log("inside function window");
    console.log(window);

})();

You will still get the same result.












When working at the global scope you have to be careful because anything you defined will be added to the global object and it could have unintended consequences.  For example I could create a global object pretty easily.  Let's use our variable global object for this demonstration.

If you type in the following code you will be creating a global object and adding it to the Window object.

var globalObj = this;

globalObj.AGlobalObject = {
    name: "My Global Object",
    myFunct : function MyFunction(){ console.log("My Global Function!")}
};

globalObj.AGlobalObject.myFunct();

console.log(globalObj);


No comments:

Post a Comment