0

I recently took a technical interview and one of the questions dealt with scope issues.

var test = {
 constructor : function() {
    var x="";
    test[sibling] = function() {
        console.log(x);
    }
  }  
};
test.constructor();
test.sibling();

When a function runs, will it test anonymously declared functions for dependencies? And when test.sibling() is initialized, will it reinitialize test.constructor()? If not, are there ways to have a function test nested anonymous functions for dependencies without initializing it?

Adam Ta
  • 1
  • 2
  • 2
    Take a look a closures: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work Once you grock it everything will fall into place. – Roberto Stelling Jan 30 '16 at 22:56
  • Check out hoisting: http://howchoo.com/g/ythlzdq1mzb/understanding-javascript-hoisting – Adam Jan 30 '16 at 22:58
  • `sibling` won't even be defined with a function until `constructor`'s been called. So it's not `sibling` initializing `constructor`, is the other way around. – MinusFour Jan 30 '16 at 22:59
  • Thank you @RobertoStelling and Adam ! – Adam Ta Jan 30 '16 at 23:00
  • 2
    also needs to be `test['sibling'] = function()` or `test.sibling = fun..`. The variable `sibling` is undefined – charlietfl Jan 30 '16 at 23:00

1 Answers1

0

That code won't even run. When test.constructor(); is invoked, test[sibling] =... is encountered, the JS engine will attempt to resolve what the sibling variable evaluates to, however sibling is not defined anywhere and an error is thrown.

But, to your specific question about how variables are resolved. It can be easy to understand, provided you understand lexical scope. In a nutshell, think of a function as a "bubble". Functions can be nested inside other functions, which creates bubbles inside of other bubbles. A function always has access to its own variables and the variables of its parent bubbles, but not sibling bubbles.

Whenever a function is nested inside another, a closure is formed. The child function "closes" around the parent's variables. The real trick is what happens when a child bubble (function) persists longer than its parent function. Normally, a function's variables are garbage collected when the function completes, but if, during the course of the parent function executing, a child function is defined and somehow returned from the parent (via a return statement or by assignment as a callback to another object, etc.), the child function will need those parent function variables at some future point in time, meaning that the parent's variables won't be garbage collected when the parent function completes. This is the nature of closures.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71