0

Please check this code. How anotherFunc is able to read this values of outerFunc, where both functions are having different scopes?

console.log("hello");

function outerFunc() {
  this.name = "Krishna";
  this.mobile = 12345;
  this.address = "India";

  function innerFunc() {
    console.log(this.name); // "krishna"
    console.log(this.mobile); // 12345
    console.log(this.address); // "India"
  }
  innerFunc();
}

outerFunc();

function anotherFunc() {
  console.log(this.name); // 'Krishna'
  console.log(this.mobile); // 12345
  console.log(this.address); //'India'
}

anotherFunc();

Update:

console.log("hello");

function outerFunc() {
  this.name = "Krishna";
  this.mobile = 12345;
  this.address = "India";

  this.innerFunc = function () {
    console.log(this.name);
    console.log(this.mobile);
    console.log(this.address);
  };
}

let func = new outerFunc();
func.innerFunc();

function anotherFunc() {
  console.log(this.name); // 'Krishna'
  console.log(this.mobile); // undefined
  console.log(this.address); // undefined
}

anotherFunc();
Mitanshu
  • 717
  • 7
  • 11
  • 4
    In all functions `this` is `window`. You're just attaching and reading properties to the same global object. – VLAZ Mar 21 '22 at 06:40
  • 1
    `this` refers to the current execution context. Loosely speaking, execution context doesn't change in normal function calls, i.e. not called with `new` or from an object(`obj.func()`). Hence, all `this` in your code refer to same execution context i.e. `window`. Check more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – Avinash Thakur Mar 21 '22 at 06:48
  • I have added another code with some modifications. Now, what is happening in `anotherFunc` here? – Mitanshu Mar 21 '22 at 06:49
  • 2
    In your updated code you are getting undefined, because the window does not have those properties. Except for `.name` which stackoverflow uses to name the iframe (*it is not outputing `Krishna` but `sifX`*) – Gabriele Petrioli Mar 21 '22 at 06:52
  • Thank you, guys! I got some idea about this. – Mitanshu Mar 21 '22 at 06:59
  • 1
    I do suggest you go through the linked duplicate. All your questions are covered there. In short, calling a function as `fn()` will use `window` as `this` (technically `undefined` but in sloppy mode it's substituted with the global object). If you call `obj.fn()` then `this` will be `obj`. If you call with `new` then a new object is initialised for the call and `this` is set to it. – VLAZ Mar 21 '22 at 07:04

0 Answers0