neo
neo

Reputation: 396

Adding properties/methods to an object globally?

I have been analyzing some javscript source codes and found that an object is declared slightly different that normal procedure and then how its used throught in the program.Its declared like this

window.ext = {};

And its properties been added in common procedure like this

ext.webRequest = {
    Property1/function2 : Property
    Property2/function2: function()
   }

My doubts are

Upvotes: 0

Views: 100

Answers (2)

gurvinder372
gurvinder372

Reputation: 68393

Is it normal to omit window.ext.webrequest and simply call ext.webrequest?

No, there are differences.

Window is a global object and also a host object. If you are not giving a window context (or global) to a property like obj.ext.webrequest JS engine will

  • First look for this object in the local context, then it parent and so one till the global context. Context are defined at function level and not at block level.

  • If the context is available locally, it will use that value and not window.ext.webrequest value.

Is there any hidden reason/advantage to declare object like that ?

One advantage that I have observed is when you want to invoke a method from the onclick attribute like

<div onclick="method1()">Click here</div>

This will automatically look for this method in global context.

But usually we want to wait for the dom to be loaded (like in JS fiddle it is a default setting), and in that case your method definitions are wrapped inside document.onload event handler function like

document.onload = function(){

   var method1 = function ()
   { 
     //some action here
   }
};

Now this method1 function is not visible in a global context, so the onclick event will fail to find this method.

But if you assign this method to a global context like this

document.onload = function(){

   window.method1 = function ()
   { 
     //some action here
   }
};

Now, it will be available for onclick event.

Upvotes: 1

KAD
KAD

Reputation: 11112

Global variables are stored the global object (this is how its called according to ECMA script specification).

In most web browsers they call the global object window and can be accessed without specifying its name.

so eventually:

window.ext = {}; and ext = {}; are equivalent (if and only if you call them within the same global scope and not in a nested scope (i.e. a function or an object scope)).

Is there any hidden reason/advantage to declare object like that ?

The advantage/reason is that declaring objects like that make them accessible at all levels since they will be declared in the global scope.

Upvotes: 1

Related Questions