0

In the following code,

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();

It prints this in the console:

outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar

The first two are pretty obvious, but I don't understand for the third and fourth one, why does the IIFE has access to self but doesn't have the access for this? I thought it creates a closure so it has access to the outer variables self and this ?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
sealife
  • 9
  • 5
  • you can use ".call(this)" instead of "()" with the anon, but _this_ is not inherited like closures are. – dandavis Sep 13 '14 at 23:41
  • 6
    Because `this` is an expression that evaluates to the *current function context*. It is *not* a variable and it is *not* inherited from a containing scope. – user2864740 Sep 13 '14 at 23:43
  • This is just a misunderstanding of how `this` works. See here http://stackoverflow.com/questions/3127429/javascript-this-keyword – elclanrs Sep 13 '14 at 23:44
  • Thanks guys, I don't know how to give vote to comments, pretty new to this site. But they are all very helpful! – sealife Sep 14 '14 at 00:02
  • A better reference is this answer (it's better because it's more complete and gets updated regularly (by me)): http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman Sep 14 '14 at 00:59
  • The comment by @user2864740 is the actual answer/explanation to the question asked. If you made it an answer I would vote for it. Answers that provide a work-around without actually explaining why or answering the question you directly asked (like the accept answer) are not as valuable in my opinion. – jfriend00 Sep 14 '14 at 01:00
  • jfriend00, I have the same opinion as you. But I don't know if there is a way to make his comment as the answer :( – sealife Sep 14 '14 at 02:24

1 Answers1

0

I'm not certain that this solves your problem, but you can bind this by passing it as an argument to the IIFE:

(function(context) {
    console.log("inner func:  context.foo = " + context.foo);
    console.log("inner func:  self.foo = " + self.foo);
}(this));

Fiddle

pdoherty926
  • 9,895
  • 4
  • 37
  • 68
  • 1
    Might as well use `call/apply`. Not really any advantage to this over a `self`, in this case, IMOHO. – user2864740 Sep 13 '14 at 23:49
  • You would be better off using #bind instead, which reassigns the `this` variable. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Mark Mar 09 '15 at 15:44