Term definitions from Eloquent JS book
Being able to reference a specific instance of a local binding in an enclosing scope—is called closure. A function that references bindings from local scopes around it is called a closure.
function multiplier(factor) {
return number => number * factor;
}
let twice = multiplier(2);
console.log(twice(5));
A good mental model is to think of function values as containing both the code in their body and the environment in which they are created. When called, the function body sees he environment in which it was created, not the environment in which it is called.
A closure is an inner function that has access to the outer scope, even after the outer scope has executed.
The closure function has access to the scope in which it was created, not the scope in which it is executed.
Abstractions hide details and give us the ability to talk about problems at a higher (or more abstract) level.
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. Higher-order functions start to shine when you need to compose operations.
Separating interface from implementation is a great idea. It is usually called encapsulation.
Since each function has its own this binding, whose value depends on the way it is called, you cannot refer to the this of the wrapping scope in a regular function defined with the function keyword.
Arrow functions are different—they do not bind their own this but can see the this binding of the scope around them.
Prototype is just a property that every function that's created has and points to object.
this
can lose context in different situations.
bind()
, the that/self pattern, and arrow functions are tools at our disposal for solving the context problems.
Factory functions give the option of creating objects without using this
at all.
this and arrow function
The arrow function partially solves the this loosing context issues in classes, but at the same time creates a new problem:
In ES6, this hacks mostly go away if you follow these rules: