Reputation: 85
I have this snippet of code:
(function(){
var d = {
sayHello: function(a){
document.writeln("Hello "+a)
}
}
this.d = d;
})();
I know that this is an IIFE, but the last line confuses me. Is it for the object d
to get outside of the scope? It's used like an API that can be accessed, right?
this.d = d
means that d
is now a variable on the scope, ready to use?
Is there any other way to accomplish that?
Upvotes: -1
Views: 47
Reputation: 340045
Since the IIFE is invoked directly with ()
there is no "context", so this
will default (in non-ES5-strictmode) to window
.
Hence the line is equivalent to:
window.d = d;
and yes, therefore exposing d
into the global namespace.
You shouldn't use this method because it's not compatible with ES5 "use strict"
which sets this = null
in the absence of an explicit context. I would recommend something like this, instead:
var MYNAMESPACE = MYNAMESPACE || {};
MYNAMESPACE.SUBPACKAGE = (function() {
...
return d;
})();
Upvotes: 3