Execution Context Flashcards
What is the global object?
JavaScript creates a global object when it starts running. It serves as theimplicit execution contextfor function invocations. In Node.js, the global object is the object namedglobal; in the browser, it’s thewindowobject. Global values such asInfinityandNaN, and global functions, such asisNaNandparseInt are properties of the global object.
What happens if you don’t use var, const, or let?
whenever you assign a value to a variable without using thelet,const, orvarkeywords (we’ll discussvarlater), the variable gets added to the global object as a property.
foo = ‘bar’;
global.foo; // => ‘bar’ (in Node)
window.foo; // => ‘bar’ (in a browser)
what happens if you don’t use var, const, or let in strict mode?
you get a reference error when assigning to the variable since it does not exist
What is execution context? How is it determined?
The execution context is a concept that refers to theenvironmentin which a function executes. In JavaScript, it most commonly refers to the current value of thethiskeyword. The only factor that determines the context is how you call the function or method.
What is the implicit execution context of a regular function call?
- Within a regular function call (e.g.,
foo()
), JavaScript sets the binding forthis
to the global object.- (Remember: in Node, the global object is called
global
; in a browser, it iswindow
.)
- (Remember: in Node, the global object is called
what is the implicit execution context of a regular function call in strict mode?
when strict mode is enabled, the implicitthisis assigned toundefinedinstead of the global object
What is the implicit exception context if you invoke a function with parentheses?
when you invoke a function with parentheses, JavaScript uses the global object as the implicit context
What is the implicit context when you call a function with ‘new’?
When you call a function withnew, its implicit context is the new object
What is the implicit context for methods?
when you call a method that belongs to an object, the execution context inside that method call is the object used to call the method
how do we supply an explicit execution context
With .call() or .apply()
How do you use .call()?
function logNum() {
console.log(this.num);
}
let obj = {
num: 42
};
logNum.call(obj); // logs 42
how do you use .call() on a method?
let obj1 = {
logNum() {
console.log(this.num);
}
};
let obj2 = {
num: 42
};
obj1.logNum.call(obj2); // logs 42
how do you use call on a method that takes arguments?
someObject.someMethod.call(context, arg1, arg2, arg3, …)
Whats the difference between call and apply?
The only difference is thatapplyuses an array to pass any arguments to the function:
someObject.someMethod.apply(context, [arg1, arg2, arg3, …])
How do you hard bind a context to a function?
using .bind():
function sumNum(num1) {
return this.num + num1;
}
let obj = {
num: 42
};
let sumNum2 = sumNum.bind(obj);
sumNum2(5); // => 47