A common metod is the following (called namespacing) - It created an encapsulated scope by immediately executing your function and returning the essential parts you need into your variable:
var yourNamespace = (function(window, undefined){
/* private code:*/
var privateVar = "foobar",
count = 0;
/* the stuff you want to use outside: */
return{
val: 5,
publicVar:privateVar,
func:function(){return ++count}
}
})(this);// `this` is a reference to `window` here
This way you have access to everything you need via your yourNamespace
variable, while still maintaining privacy and not polluting the global object. It's called namespacing and uses the closure paradigm. You can also hand over functions to work with private (for the enclosing scope non-visible) variables.
One reason for handing over undefined was, that in ES3 undefined was writable, which it is not the case anymore in ES5. Handing over over this
as parameter shortens the lookup by creating a direct reference to the global window
object in the scope. However, be very cautious - in ES5 strict mode this
is not the window anymore but resolves to undefined
!! So this is not recommended anymore!
Another reason for handing over window and undefined is that now that these are variable names, a minifier could compress them to a single letter.
if(myVar == undefined)
// could be compressed to:
if(a==x)
EDIT to your question:
The this
will not change in your example, you need one of the following solutions:
(function(myElement){/*your code*/})( document.getElemetById("myElementId") );
// or:
(function(){
var myElement = document.getElemetById("myElementId");
/* your code */
})();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…