How to use objects for storing global variables? Best practice
I'm new to OOP in JavaScript, since I always worked with some frameworks
and my own simple constructs, but never thought about what happened under
the hood. Now, I want to tackle one problem which many JS programmers face
- global variables. I know it's a bad practice to make global variables
and many suggest using objects istead. And this is where a problem pops
up. I do not know what is the best way to create an object and to call it
somewhere in the application to get global variable values. For example,
I'm not sure whether to use init fucntion or not and how to return a
global variable value (through a function or by "dot" notation). I've seen
a bunch of examples concerning objects but they looked different in style.
Imagine a concrete example. I want to store global variables in an object
- window's height and window's width. To make it cross-browser I will use
this code
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
w = w.innerWidth || e.clientWidth || g.clientWidth, // this is global
variable
h = w.innerHeight|| e.clientHeight|| g.clientHeight; // and this is
global varibale too
So, how to apply this code inside an abject and how to get these global
variables' values somewhere in the application?
No comments:
Post a Comment