1

I have the following code snippet.

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();

with the following results.

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

I have a few questions about this code snippet.

  1. What is the idea of putting the nested function inside the outer function. How would that benefit real life code?
  2. I'm also struggling with the 'this' keyword, I always thought 'this' represented the global context, so I'm confused with how it works in the outer function but not in the inner function.
Code Junkie
  • 7,602
  • 26
  • 79
  • 141

2 Answers2

2

You really have two different concepts in your question:

  1. this keyword.
  2. closures.

Trying to use this inside a closure is known to confuse many people.

What is the idea of putting the nested function inside the outer function. How would that benefit real life code?

There is very good documentation about closures. If you are not familiar with closures, the gist is that it remembers the environment where the function was defined.

E.g. self.foo does return the correct value.

Applications are mostly functional programming / currying.

E.g. self.foo inside the closure does return the correct value but you did not have to pass the value to the function.

I'm also struggling with the 'this' keyword, I always thought 'this' represented the global context, so I'm confused with how it works in the outer function but not in the inner function.

Inside this block:

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

we are not using an object method, but a simple call. Because you are not using strict mode, this defaults to a global object.

In this other part:

    console.log("outer func:  this.foo = " + this.foo);
    console.log("outer func:  self.foo = " + self.foo);

we are inside an object method; this refers to the object myObject.

exercices

  1. what happens if you use strict mode inside the closure?
  2. what happens if you do window.foo = 'window foo'; before-hand?
Community
  • 1
  • 1
dnozay
  • 23,846
  • 6
  • 82
  • 104
0

Maybe you can see this to understant the "this" in javascrpt.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

afei
  • 11
  • 2