3

There's something about object, execution context in JS that I don't understand.

When we create an object, does it create an execution context ? since an execution context is created when a function is invoked. And if it doesn't, so the object is just like the others variable in the actual execution context ?

Thank you.

Quoc-Hao Tran
  • 1,012
  • 2
  • 11
  • 18

1 Answers1

5

When we create an object, does it create an execution context ?

No.

since an execution context is created when a function is invoked.

That's true, but creating an object is different from invoking a function.

And if it doesn't, so the object is just like the others variable in the actual execution context ?

The object exists in memory, and a reference to it exists in any variable or property you stored it in. If you store it in a variable, that variable is held in a lexical environment object associated the execution context where the variable was declared.

A concrete example might help:

function foo() {
    var n = 42;
    var o = {};
    console.log(n, o.toString()); // 42, [object Object]
}
foo();

Calling foo creates an execution context and a lexical environment object associated with it. The n and o variables are bindings stored in that lexical environment. The n binding's value is the primitive number 42. The o binding's value is a reference to the object. The object itself exists elsewhere in memory.

+−−−−−−−−−−−−−−−−−−−−+
| Execution Context  |
+−−−−−−−−−−−−−−−−−−−−+   +−−−−−−−−−−−−−−−−−−−−−+
| Current Lex Env    |−−>| Lexical Environment |
| (some other stuff) |   +−−−−−−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−−−−−+   | n: 42               |   +−−−−−−−−+
                         | o                   |−−>| Object |
                         | (some other stuff)  |   +−−−−−−−−+
                         +−−−−−−−−−−−−−−−−−−−−−+

But again, that context and its lexical environment are created by the call to foo, not by creating an object.

Once foo returns, if no closures were created within foo, the execution context and its associated lexical environment are eligible for garbage collection.

Getting a bit far afield of your question: If we'd created a closure within foo and retained a reference to it even after foo returned, the lexical environment would be retained by that closure; more on closures in this question and its answers.

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639