Sven
Sven

Reputation: 13295

When is it okay to attach properties to window?

While browsing, I frequently take a look at the source code of webpage to check how certain things have been realized.

One thing I frequently see is stuff like: window.myApp.apiKey = 12345; or window.myApp.welcomeMsg = "Hello there!";

I always was under the impression that it's bad practice to attach properties to the window object (like explained in this accepted answer), but it looks like myApp is used as a kind of namespace & since it's often the brand name, it's unlikely to clash with anything.

Still – how is it okay to do it this way, are there any indicators for that? (i.e. when I know no 3rd libraries will be used in the project, which can change quickly in real life).

Upvotes: 0

Views: 693

Answers (1)

John
John

Reputation: 13739

In general I would use the following approach...

if (typeof window['myApp']=='undefined') {alert('its okay.');}
else {alert('Error: native API added, have AJAX message server, email you.');}

...of course whether or not you should do this is subjective, I personally use...

var option = new function() {this.name = '';}
option.whatever = 'this string';
alert(option.whatever);//'this string'

...however I may rename it and revise it in the future as I do with all my code.

As Ingo Bürk points out in the comments it seems ultimately everything is an object child of the window object, the only difference between those objects is the context and how you can interact with them (e.g. you can not delete an object defined by var though you can delete window.myObject when it is defined as window.myObject = 1;.

For more in-depth information refer to the answer for 'Javascript global variables'.

Upvotes: 1

Related Questions