1

Based on my knowledge of JavaScript and let, a variable defined with this keyword is available after it has been defined throughout an entire scope (not necessarily function execution context like var).

Quoting from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

"Variables declared by let have their scope in the block for which they are defined, as well as in any contained sub-blocks."

It is also my understanding that directly within a method (member function), this refers to the object, but within all other functions, this refers to the global object. Given this, I am confused by the result below:

let a = 7;
let b = {
  a: 13,
  foo: function() {
    (function() {
      console.log(this.a);
    })();
  }
};

b.foo();

I would have expected the value 7. Instead, I get undefined on Chrome. On Firefox it seems nothing is logged.

I get the same behaviour if I replace the IIFE with a call to a function defined only within foo. Can anyone clarify what has happened here? Is that IIFE not part of a contained sub-block?

Ele
  • 33,468
  • 7
  • 37
  • 75
user137364
  • 305
  • 1
  • 7
  • `this` does not have an `a` value. If you want to access the `a` from the first line then use `console.log(a);` – Alien11689 Nov 04 '18 at 18:49
  • 3
    From the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Scoping_rules_2): "_At the top level of programs and functions, let, unlike var, does not create a property on the global object_" --> `window.a` was never created. – Teemu Nov 04 '18 at 18:49
  • Thanks, Teemu, that would certainly explain it!!! – user137364 Nov 04 '18 at 18:56
  • not trying to thread jack but even when switching the let to a var it comes back undefined, why? – Austin Bentley Nov 04 '18 at 19:15
  • @AustinBentley: it comes back as 7 for me if I replace the 'let a = 7;' with 'var a = 7;' Did you maybe change the 'let' to 'var' for b instead? I can see that maybe having no effect. – user137364 Nov 04 '18 at 19:29
  • when you use this inside of nested function 'this' keyword more likely will loose reference to the object that it is inside of... and in this situation 'this' is reference to the GLOBAL OBJECT .to solve this before the IIFE you have to write 'var self = this;' and replace 'console.log(this.a);' with 'console.log(self.a);' – mohammad zein Nov 04 '18 at 19:52
  • i was using js fiddle and it wasn't working so i'm just going to attribute my problem to js fiddle – Austin Bentley Nov 04 '18 at 20:09
  • @AustinBentley Please don't blame jsFiddle, `var` works as described in a fiddle too, but you've to set Load Type to head/body instead of onload/DOM ready, to really declare the variable in the global scope. – Teemu Nov 05 '18 at 06:12
  • @teemu. I wasnt blaming as much as attributing the area where my problem was from. Thank you for the tip! – Austin Bentley Nov 05 '18 at 15:52

0 Answers0