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.