Can I add attributes to 'window' object in javascript?
Can I add any random attribute to 'window' object in javascript?
Yes, just like you've shown.
Does it have any side effects with any libraries?
No, not unless you use a library which sets a property you then overwrite.
And is it cross-browser compatible?
Yes, completely.
Having said that, this practice is generally frowned upon. You could end up overwriting something you don't want to.
In all browsers, window
is the javascript global namespace. Every property or method 'lives' in that namespace. So if you assign a property to window
, it is in effect a global variable.
example:
window.myConstant = 5;
function multiply(val){
return myConstant * (val || 1);
}
multiply(10); //=> 50
multiply(); //=> 5
You have to be cautious with javascript frameworks. For instance, if you declare window.JQuery
, and use the JQuery
framework, the JQuery
namespace will be replaced by your assignment, rendering it useless.
Yes, you can, but in general you shouldn't.
The window
object is also the JS default "global" object, so all global variables get added there.
You're unlikely to break anything unless you overwrite a property that's already there, but it's considered bad practise to dump variables on window
, or otherwise create lots of global variables.