The target
- Be able to define and call functions in a variety of ways
- The ability to say and change the direction of this inside a function
- Be able to describe the characteristics of a strict model
- The ability to pass functions as arguments and return values
- Be able to say what closures do
- Be able to name two conditions for recursion
- Be able to tell the difference between deep copy and shallow copy
directory
- Function definition and call
- this
- Strict mode
- Higher-order functions
- closure
- recursive
1. Function definition and invocation
1.1 Definition of functions
- Function keyword (named function)
- Function expressions (anonymous functions)
- new Function()
Var fn = new Funciton(' 1',' 2'... , 'function body ')Copy the code
- All parameters in Funcion must be in string format
- The third method is less efficient to implement and is not easy to write, so it is less used
- All functions are instances (objects) of Funciton
- Functions are also objects
1.2 How to call functions
- Common function
- Object methods
- The constructor
- Bind event function
- Timer function
- Execute function immediately
2. this
2.1 Reference to this in functions
These “this” references are determined when we call the function. Depending on how this is called, it refers to our caller.
- Normal function call: window
- Constructor calls: Methods in the instance object prototype object also point to the instance object
- Object method call: The object to which the method belongs
- Event binding method: Bind event objects
- Timer function: window
- Execute the function :window immediately
2.2 Change the this pointer inside the function
JavaScript provides a number of function methods to help us handle this pointing problem in a more elegant way. Commonly used methods include bind(), call(), and apply().
1. The call method
The call() method calls an object. This is simply the way a function is called, but it can change the this direction of the function.
fun.call(thisArg,arg1,arg2,...)
Copy the code
2. Apply method
The apply() method calls a function. This is simply the way a function is called, but it can change the this direction of the function.
Fun. Apply (thisArg, [argsArray])Copy the code
- ThisArg: This value specified when fun is run
- ArgsArray: The value passed must be contained in the array
- The return value is the return value of the function, because it is the calling function
3. The bind method
The bind() method does not call the function. But you can change the this point inside the function
Fun. Bind (thisArg, arg1, arg2,...).Copy the code
- ThisArg: This value specified when fun is run
- Arg1,arg2: Other arguments to pass
- Returns a copy of the original function modified with the specified this value and initialization arguments
2.3 Call apply bind summary
Similarities:
You can change the this pointer inside the function.
The mark:
- Call and Apply call the function and change the this reference inside the function.
- Call does not pass the same parameters as apply. Call passes aru1,aru2… Apply must be array [arg]
- Bind does not call a function; it can change the this pointer inside a function
Main application scenarios:
- Call often does inheritance
- Apply is often associated with arrays, such as arrays Max and min with mathematical objects
- Bind does not call the function, but also wants to change the this pointer. For example, change the this pointer inside the timer
3. Strict mode
3.1 What is strict mode
JavaScript provides strict mode in addition to normal mode. ES5’s strict mode is a way to adopt restrictive JavaScript variants, that is, to run JS code under strict conditions.
Strict mode is only supported in IE10 or later, and is ignored in older browsers.
Strict mode makes some changes to normal JavaScript semantics:
- Eliminates some of the irrationality and rigor of Javascript syntax, and reduces some of the quirks.
- Eliminate some unsafe places in code operation 3, ensure the safety of code operation.
- Improve compiler efficiency and speed
- Disabled some syntax that may be defined in future releases of ECMAScipt, paving the way for future releases of Javascipt. Such as some reserved words such as: class, enum, export, extends, the import, super can’t do the variable name
3.2 Enabling the Strict Mode
Strict patterns can be applied to entire scripts or to individual functions. Therefore, in use, we can divide strict mode into strict mode for scripts and strict mode for functions.
1. Enable strict mode for the script
To enable strict mode for the entire script file, place a specific statement “use strict” before all statements; (or “use strict”) .
<! -- Turn on strict mode for the entire script (script tag) --> <script> 'use strict'; </script> <script> (function () {'use strict'; }) (); </script>Copy the code
2. Turn on strict mode for functions
To turn a function on strict mode, make “use strict”; (or “use strict”) The declaration precedes all statements in the function body.
<script> function fn() { 'use strict'; } function fun() {function fun() {} </script>Copy the code
3.4 Changes in Strict mode
Strict mode makes some changes to the syntax and behavior of Javascript.
1. Variable provisions
- In normal mode, if a variable is assigned without a declaration, the default is global. Strict mode forbids this use, and variables must be declared with the var command before they are used.
- Do not delete declared variables. For example, the delete x; The grammar is wrong.
2. In strict mode, this refers to the problem
- Previously, this in global scoped functions referred to the window object
- This is undefined in a function in global scope in strict mode
- Previously, constructors could be called without new, as in normal functions, this refers to a global object
- In strict mode, this is an error if the constructor is not called with new
- The new instantiated constructor points to the created object instance
- The this in the timer still points to the window
- Event, object, or point to the caller
3. Function changes
- Functions cannot have arguments with the same name.
- Functions must declare at the top level that new versions of Javascript introduce “block-level scope “(introduced in ES6). For compatibility with the new version, it is not allowed to declare functions inside non-function blocks of code.
More references:
Developer.mozilla.org/zh-CN/docs/…
4. Higher-order functions
Higher-order functions are functions that operate on other functions, taking functions as arguments or output functions as return values.
<script>
function fn(callback) {
callback&&callback();
}
fn(function() {alert('hi')})
</script>
Copy the code
<script>
function fn() {
return function() {}
}
fn();
</script>
Copy the code
So f sub n is a higher order function.
A function is also a data type that can also be passed as an argument to another argument. The most typical is as a callback function.
5. The closure
5.1 Variable scope
Variables can be divided into two types depending on their scope: global variables and local variables.
- Global variables can be used inside functions
- Local variables may not be used outside functions
- Local variables in this scope are destroyed when the function completes execution
5.2 What is a Closure
A closure is a function that has access to variables in the scope of another function. ——————Javascript advanced programming
Simply put, a scope can access local variables inside another function.
Closures are generated when a function has a local variable that other scopes can access. The function produced by this variable is called a closure function.
The main thing about closures is that they extend the scope of variables
5.5 Closure cases
- Cycle register click events
- SetTimeout () in the loop
- Calculate the price of a taxi
5.6 Closure summary
1. What are closures?
A closure is a function (one scope can access a local variable of another function)
2. What do closures do?
It extends the scope of the variable
6. Recursion
6.1 What is recursion?
A function is recursive if it can call itself internally.
Simple to understand: a function that calls itself internally is a recursive function
Recursive functions act as loops.
Since recursion is prone to “stack overflow” errors, an exit conditional return must be added.
6.3 Using recursion: Return the corresponding data object according to the ID
Var data = [{id: 1, name: 'home appliance, goods: [{id: 11, gname:' fridge, goods: [{id: 111, gname: 'haier'}, {id: 112, Gname: 'beauty'}}, {id: 12, gname: 'washing machine'}}, {id: 2, name: 'clothing'}]; // We want to make the data object that can be returned by input id number // 1. Function getID(json, id) {var o = {}; json.forEach(function(item) { // console.log(item); If (item.id == id) {o = item; return item; // console.log(item); } else if (item.goods && item.goods. Length > 0) {o = (item.goods && item.goods getID(item.goods, id); }}); return o; } console.log(getID(data, 1)); console.log(getID(data, 2)); console.log(getID(data, 11)); console.log(getID(data, 111));Copy the code
6.4 Shallow Copy and Deep Copy
- Shallow copies copy only one layer, and deeper object levels copy only references
- Deep copy copies multiple layers of data at each level
- Object.assign(target,… Sources) ES6 new methods can be shallow-copied
Encapsulate functions for deep copy
Var obj = {id: 1, name: 'Andy ', MSG: {age: 18}, color: ['pink', 'red']}; var o = {}; Function deepCopy(newobj, oldobj) {for (var k in oldobj) { Oldobj [k] var item = oldobj[k]; If (item instanceof Array) {newobj[k] = []; deepCopy(newobj[k], item); } else if (item instanceof Object) { // 3. Newobj [k] = {}; deepCopy(newobj[k], item) } else { // 4. Newobj [k] = item; } } } deepCopy(o, obj); console.log(o);Copy the code