aleith
aleith

Reputation: 444

How does `this`context work in immediately self executing functions?

Can someone explain to me what is happening here that causes my properties to be attached to the window object:

var MyObject = (function () {    
    this.property1 = "prop1";

    return this;
})();
// window.property1 now exists as well as MyObject.property1

Is this the "right" way to do this:

var MyObject = (function () {
    var MyObject = {};
    MyObject.property1 = "prop1";

    return MyObject;
})();
// only MyObject.property1 now exists

Upvotes: 1

Views: 58

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

You are calling a function. Whether it's anonymous or not, it is a function. Functions have context, the this keyword.

You have provided no context, so window is used.

Try:

var MyObject2 = (function() {
    this.property1 = "prop1";
    return this;
}).call(this);

Here you are explicity defining the context as "whatever the current context is" - of course, this may again be window, but then again it may not - can't really tell without seeing more code.

Upvotes: 5

Related Questions