0

i have declared global variable as follows:

var glob = "smiley";

However i want to call it from inner scope of 3 functions. Like this:

// Global is finally found!
(function(){
    // glob not found, then browser searches upwards
    (function(){
        // glob not found, then browser searches upwards
        (function(){
            var joe = glob;
            var win = window;
        })();
    })();
})();

Since window is a javascript keyword, it is taken from global scope directly, without searching outer scopes? And is there any efficient way how to call a global variable in Javascript directly? Without searching in all previous scopes?

Fusion
  • 3,603
  • 5
  • 30
  • 42
  • 2
    No, `window` is not a keyword. It's just a variable like all others. – Bergi Nov 25 '15 at 13:26
  • What's the problem with searching in outer scopes? It's not like you have to do it by hand with pen and paper. You should be able to get it with `window.glob` btw, or `win.glob`in your example. – Arg0n Nov 25 '15 at 13:27
  • 1
    Implementations don't necessarily perform a sequential search through each execution context looking for variables. They may create an index of variables available to a certain scope when creating each context. Or they might have other, more efficient ways of looking up the scope chain. – RobG Nov 25 '15 at 13:29
  • @Bergi—are you sure that's a duplicate? – RobG Nov 25 '15 at 13:31
  • @RobG Just what i was thinking.. – Arg0n Nov 25 '15 at 13:32
  • @RobG: No, "*What does this pattern do?*" and "*How to solve this problem?*" are not exactly the same question, but when the pattern solves the problem (canonically) closing seemed fine to me. Feel free to reopen and answer instead. – Bergi Nov 25 '15 at 13:35
  • initialize to `window.glob = 'smiley';` I'd be careful with using the term **call** when you are trying to reference a variable. –  Nov 25 '15 at 13:48

0 Answers0