Many developers do not think deeply about the results of a program that is not the same as expected, only to avoid using other methods to achieve the goal.
One. Closures
Regardless of the way the function is passed to the lexical scope , it holds a reference to the original definition scope, and no matter where the function is executed, the closure is generated. Reutrn a function, callback a function
It can be seen from the above two necessary conditions for closures, one is that the principal is a function (and an intrinsic function), and the second is that the function is executed outside the lexical scope
Two. About this
This is dynamically bound when the function is called, not when it is written. the point of this is entirely dependent on where the function is called
(1) Call location
The call location is where the function is called in the code (not the declared location). The most important thing is to parse the call stack (just to get to all the functions that are called at the current execution location). The call location that we care about is in the previous call to the function that is currently executing
(2) Bind rule //find the call location and determine which binding rule is used
- The default binding. The most common method of invocation, directly calling without any adornments
Although the binding rule of this is entirely dependent on the call location, the default binding is bound to the global object only if it is run under non-strict mode, regardless of where the call to Foo () is, and this is bound to undefined
- Implicit binding. Whether the call location has a context object , or whether it is owned by an object or contains
When a function reference has a context object, the implicit binding rule binds this to the context object in the function call
3. Explicit binding. Call () apply ()
4. New binding
Note : If you pass null or undefined as the bound object of this to call, apply, or bind, these values are ignored at invocation and are actually applied by default binding rules
Summary:
if you want to determine the this binding of a running function, you need to find the direct call location of the function. Once found, The following four rules are applied to determine the binding object of this.
1. Called by new? Binds to the newly created object.
2. Called by call or apply (or bind)? Binds to the specified object.
3. Called by the context object? Binds to that context object.
4. Default: Bind to undefined in strict mode, otherwise bind to global object.
Three. Objects
JS essay (You don't know the JS)