When creating a function, they are compiled at runtime. The function is called when you call them.
Let me clarify a bit:
You can have any number of function contexts, and each function calls creates a new context.
//Global Context var helloWorld = "hello world!"; function foo(){//execution context function bar(){//execution context console.log('bar'); } } foo();
So, in the above code function, foo is called and creates a new context for the foo function, and the execution context for the bar is created only after it is called, but it has been compiled for the duration of the execution.
When a script loads for the first time by a browser, it enters the global execution context by default. If you call a function in the global scope, the sequence flow of your program enters the called function, creating a new execution context and dragging that context to the top of the execution stack.
Now let's talk in detail about the execution context:
So, every time a function is called, a new execution context is created. Each call to the execution context has 2 stages:
1. stage of creation:
When a function is called, but before it executes any code inside, do the following: create a chain of scopes, create variables, functions and arguments, and define the value "this".
2. stage of activation:
Assigning values, function references, and code execution.
Now let's find out a little about the execution context :
function foo (a, b, c) { function z(){alert('Z!');} var d = 3; } foo('foo','bar');
ExecutionContext in a call to foo (): Step 1: arguments are created
ExecutionContext: { arguments: { 0: 'foo', 1: 'bar', length: 2, callee: function() //Points to foo function } }
Step 3a: creating a variable, arguments
ExecutionContext: { arguments: { 0: 'foo', 1: 'bar', length: 2, callee: function() //Points to foo function }, a: 'foo', b: 'bar', c: undefined }
Step 3b: creating a variable, function
ExecutionContext: { arguments: { 0: 'foo', 1: 'bar', length: 2, callee: function() //Points to foo function }, a: 'foo', b: 'bar', c: undefined, z: function() //Created z() function }
Step 3c: variable instance, variables
ExecutionContext: { arguments: { 0: 'foo', 1: 'bar', length: 2, callee: function() //Points to foo function }, a: 'foo', b: 'bar', c: undefined, z: function(), //Created z() function, d: undefined }
Step 4: set this value
ExecutionContext: { arguments: { 0: 'foo', 1: 'bar', length: 2, callee: function() //Points to foo function }, a: 'foo', b: 'bar', c: undefined, z: function(), //Created z() function, d: undefined, this: window }
After creating an ExecutionContext, the function runs its code from the first line until it finds a return or finishes work. Each time this code tries to access a variable, it is read from the ExecutionContext object.