Scope and Context
The differences between scope and context are as follows:
- Every function invocation has both a scope and a context associated with it. Fundamentally, the scope is function-based and the context is object-based.
- Scope pertains to the variable access of a function when it is invoked and is unique to each invocation.
- Context is always the value of the keyword, which is a reference to the object that owns the currently executing code.
From that point, each invocation of a function creates a new execution context (called Function Context).
Each time a new invocation context is created, it is appended to the top of the execution stack.
The browser always executes the current execution context at the top of the execution stack.
When it is completed, the context is removed from the top of the stack, and control returns to the execution context below it.
An execution context can be divided into a creation and execution phase.
In the creation phase, the interpreter first creates a variable object (also called an activation object). The variable object is composed of all the variables, function declarations, and arguments defined inside the execution context.
The scope chain initializes next, and the value of this is determined last. Then, in the execution phase, code is interpreted and executed.
For each execution context, there is a scope chain coupled with it.
In this example, the
this reference in the handle function points to the window object of the browser BOM model.
The handle event is executed in the global context of the application.
this reference points, in this example, to the window object of the BOM.
The method of a node always executes the callback in the context of the node to which the event handler is bound.
Call and Apply
With these two methods, inherent to all functions, you can execute any function in any desired context:
- The call function requires that arguments are listed explicitly.
- The apply function enables you to provide the arguments as an array.
ECMAScript 5 (ES5) introduces another method of setting the execution context, a bind function called the
The method is used to manipulate context. It returns a
newfunction that is permanently bound to the first argument of bind no matter which function is used.