user251291
user251291

Reputation:

Javascript Modules

I have the following code. It's a JavaScript module.

(function() {

   // Object
   var Cahootsy;

   Cahootsy = {
       hello: function () {
           alert('test');
       },
    };

    (Cahootsy.scope = (function() {
        return this;
     })()).Cahootsy = Cahootsy;

    return Cahootsy;

}).call(this);

I don't understand the section:

    (Cahootsy.scope = (function() {
        return this;
     })()).Cahootsy = Cahootsy;

I think it is creating an object referencing 'this' module and then assigns the Cahootsy variable to a global Cahootsy variable. What I don't understand is why 'this' needs to be assigned to Cahootsy.scope

Upvotes: 10

Views: 427

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

You can break it down a little, like so:

var getScope = function() {return this;}
Cahootsy.scope = getScope();
getScope().Cahootsy = Cahootsy;

What it does is gets the global scope (usually window, but not always). Then it creates a link from Cahootsy to the global scope via the object's scope property, and a link the other way via the scope's Cahoosty property.

The result is that, in a browser, you would get window.Cahootsy is the object, and window.Cahootsy.scope goes back to the window.

Upvotes: 6

SLaks
SLaks

Reputation: 887469

(function() { return this; })() is a trick to return the global object.

This statement sets Cahootsy.scope to the global object (for future use), and also sets the Cahootsy property of the globalobject to expose Cahootsy to the outside world.

Upvotes: 3

Related Questions