0
let a = {};
console.log(window.a);
console.log(a);

why is result:

undefined
Object

rather than both Object

Updated: How do I access global a from within this function without going to Var?

let a = {
    func1() {
        let a = 'something';  // local a

        // need to access the global a not the local a here
        window.a.func2(); 
    },
    func2() {
    }
};
Brobic Vripiat
  • 176
  • 2
  • 12
  • 3
    plase look at the duplicate's first answer under the chapter: 'Creating global object property'. in short, let creates an own scope and window is in the global scope. – Nina Scholz Nov 13 '20 at 18:53
  • See update above. – Brobic Vripiat Nov 13 '20 at 19:11
  • 2
    you can not access same named variable fomr outer scope. solution: take a different name, or take a closure for saving the outer scope's value. – Nina Scholz Nov 13 '20 at 19:14
  • That's how `let` works - it was designed this way intentionally. If you need the old behavior you need to use `var`. The reason people suggest using `let` is exactly to prevent this kind of behavior in polluting the global object. But if you intentionally want to pollute the global object then you have every right to use `var` – slebetman Nov 13 '20 at 19:53
  • I see your point but in this case LET provides more pollution because it prevents me from qualifying my "a.func()" like this "window.a.func()" so it is more likely to conflict with other local variables of the same name like shown above. VAR allows the qualification so the local space won't be polluted by the global 'a' function call. – Brobic Vripiat Nov 13 '20 at 21:04
  • You don't need access to "the global a not the local a here". Just call `this.func2()` – Heretic Monkey Nov 13 '20 at 21:05

0 Answers0