Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is correct to think of all JS code & variables as being a property of an execution context?

Tags:

javascript

I may be wrong, but it seems safe to conceptualize everything in JS code as being a property of an execution context (either a global or function or eval() execution context). Why?

  • every execution context has unique lexical/var environments as properties. (New run = new ex. context = new instances of variableEnv objects = new variables with new references)

  • and these lexical/var environments contain all your variables (identifier-value mappings).

Closures might be a good supporting example:

function function0(sizevar) {
    s = sizevar * 2;
    return function function1() {
	    console.log(s);
        console.log(sizevar);
    };
}
    
var size12 = function0(12);
var size14 = function0(14);
size12()
size14()

So from the above^, when you return an embedded function1, you’re returning a reference to a function instance/object that’s a property of one specific execution context’s lexical/variable environment.

And when function0() returns function1(), scope chain is tied to an execution context’s state (i.e. its variableEnv), even if that execution context is done executing.

Is this a correct or incorrect way to think of JS variables?

Anyone have a link/code/image of an actual JS execution context object?

like image 666
AnonEq Avatar asked Jan 25 '26 22:01

AnonEq


1 Answers

Is this a correct or incorrect way to think of JS variables?

Yes, this is a fine way to conceptualise scopes. But remember it only is a concept, and an actual js engine might implement it different (especially, optimise the heck out of it). It will still have the same results as the model, though.

Anyone have a link/code/image of an actual JS execution context object?

I found several good illustrations at

  • http://speakingjs.com/es5/ch16.html#_handling_closures_via_environments
  • https://dmitryfrank.com/articles/js_closures
  • How do JavaScript closures work at a low level?
  • https://mrale.ph/blog/2012/09/23/grokking-v8-closures-for-fun.html

(but won't copy the images here to respect the copyright of the respective authors)

like image 166
Bergi Avatar answered Jan 27 '26 11:01

Bergi