0

I'm learning javascript and writing some simple console (chrome console) apps to familiarize myself with it.

I have the following code:

var john = {
    name: 'John',
    yearOfBirth: 1990,
    calculateAge: function() {
        console.log(this);
        console.log(this.yearOfBirth);

        function innerFunction() {
            console.log(this);
        }

        console.log("inner function called");
        innerFunction();
    }
}

john.calculateAge();

Which yields this surprising ( to me, at least ) output:

script.js:64 {name: "John", yearOfBirth: 1990, calculateAge: ƒ}
script.js:65 1990
script.js:71 inner function called
script.js:68 Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, `close: ƒ, …}`

So I would have thought that when innerFunction is called the object in scope (that, what 'this' refers to) would be either the object John or the function ( which is also an object in javascript, right? ) innerFunction. Instead it is the global object, in this case Window. Why? What is the rule here that I am not seeing?

I am asking about this specific example. So, yes, the question is unique. How so? It is mine.

Dewey Banks
  • 323
  • 1
  • 7
  • 19
  • 1
    `innerFunction` is not tied to any specific context (and therefore it will execute in the global context, unless `call` or `apply` have been used at call-time to modify it's context, which they haven't in your example). It's just a function whose declaration happens to be inside of a function executed in the context of the object referenced by `john`. I feel that this explanation probably won't help you wrap your head around it much more, however. Try `innerFunction.call(this)` and see the difference. – Adam Jenkins Oct 12 '17 at 00:18
  • 1
    This might help too - change it to `this.innerFunction = function() { ... }` instead of `function innerFunction() { ... }` and then do `this.innerFunction()` instead of `innerFunction()` and you'll see that the context changes because the function is being tied to a specific execution context. – Adam Jenkins Oct 12 '17 at 00:22
  • 1
    I too disagree that this is a dupe... The linked questions asks "How do I do" and this question asks "Why is this so?". There is probably a dupe in existence but this one is not it. To answer OP: Generally a function's `this` will be window UNLESS it was specifically called as an object method. [See MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Function_context). Converting `innerFunction` to an arrow function would actually make the inheritance work as you expect as well. – ProdigySim Oct 12 '17 at 00:27

0 Answers0