JSCORE01
Table of contents
4. Anonymous functions solve global pollution
10. Square bracket attribute syntax
foreword
JSCORE01 study begins
1. Statement upgrade
- Error reporting solution: Let the user correct the code by himself -- it must be a code that accurately expresses the user's thoughts, but it is troublesome
- Automatic correction: the system helps the user to correct it -- making the programmer comfortable, but it is possible that the automatic correction may be wrong
- Amendment Act: Declared Enhancement Act
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Statement Operation 09:37</title> </head> <body> <!-- statement: create a space in memory, give a name to store something, You can find this thing by this name in the future Mainly divided into two categories: - variable: some fixed value - function: values that can be run, use()trigger run --> <script> // Declare variables and assign values at the same time var a = 5 var b = 10 var c = true // Declaring a function while assigning function show() { } function talk() { } // // Interview test points: JS engine is different from other programming languages // Declare boost: // -- Original intention: The JS engine will `intelligently` correct unreasonable codes into reasonable codes // Unreasonable: In the mathematical operation expression, the value involved in the operation must be a number type, so it is reasonable // For unreasonable code, there are two options // 1. Error: C Java - strongly typed language // 2. Automatic correction: PHP JS - weakly typed language; the JS engine will read the code first, correct the unreasonable ones, and then execute console.log(10 + true) // Change to: console.log(10 + 1) and run again; implicit type conversion // Amendment Act: Variables must be declared before use // So: the JS engine will automatically hoist all declaration operations to the top of the scope function x() { // clg : can quickly generate console.log console.log(111); } x() //222 function x() { console.log(222); } x() //222 </script> </body> </html>
Second, the host window
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>window 10:22</title> </head> <body> <!-- host environment: parasitic host JS The language has two main host environments - Node.js: Provides a set of operational server API -- Skill - browser: Provides a set of operating browser API -- Skill API: API -- some code to operate the software --> <script> // Press ESC to exit the state after automatic generation, and only when you write code will you be prompted console.log(window) //clg // window: called the global object, which stores `skills` that can be used globally // window.alert('Hello, window') // Setting: When using a variable or function, if the variable has not been declared, it will be automatically searched and used from the window // alert('hello world!') // global variable pollution // The skills provided by the system are all stored in the window object // It can be considered that the window object is dedicated to storing system skills // var: In which scope is written, the variable will be declared in that scope // --- If written directly in the script, it will be stored in the window object, causing pollution (customized values and official values are put together, which is pollution) var a = 10 // The variable b is not declared with var, another scenario is triggered: // Automatically search from the window, b is added through the new syntax of the object's properties b = 20 // window.b = 20 </script> </body> </html>
3. Breakpoint function
4. Anonymous functions solve global pollution
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>function scope 10:43</title> </head> <body> <!-- The local scope as opposed to the global scope(function scope) --> <script> // Create function scope -- provides the fastest syntax: anonymous function self-invocation // function x() { } // x() // var x = function () { } // x() // x is directly replaced with a function, surrounded by (), recognized as a whole // When actually writing JS, in order to avoid global pollution, you will choose to write an anonymous function self-tuning in the script first // Then write the code here (function () { var a = 10 // You need to use the breakpoint debugging tool provided by the browser to visually see the local scope console.log(1) // var: In the current scope, declare the variable // -- Misunderstanding: var must be globally polluted --- error; it will only be declared in the script // If the declared b variable cannot be found, look it up from window b = 20 // window.b = 20 // Amendment Act -- Declare Enhancement Act // Declarative actions are hoisted to the top of the scope before they are actually run // var b is in the local scope, b=20 will be assigned to this b variable, and will not pollute // var b })() console.log(window) </script> </body> </html>
Five, the scope chain
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Scope chain 11:23</title> </head> <body> <!-- scope chain: When there is a scene where multiple scopes are nested, If using 1 variable, Find and use according to the principle of proximity --> <script> var x = 10 function a() { function b() { var x = 20 function c() { function d() { console.log(x) } d() } c() } b() } a() </script> </body> </html>
6. Closure
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Closure 11:33</title> </head> <body> <!-- Closure closure : closed,enclosed surrounded,pack Closure: Describes a state of function scope -- are stored in other functions' scopes inside, to bind reason: prevent release shortcoming: free memory, The function scope that should have been released cannot be released; Occupies memory forever until destroyed --> <script> // Function scope: Yes The scope generated by the function `runtime` `temporary` // Temporary: After the function is executed, its scope will be released from memory to save memory function y() { var b = 20 var c = 30 var d = 40 // Theoretically: After the function finishes running, it will be released automatically to save memory // But: the z function below uses the b and c variables generated by the y function // In order to ensure that it can run normally, the z function saves the scope of the y function in itself // -- Goal: Prevent self-dependent content from `running away` // -- Counterexample: Liangliang applied for a swimming card, but the swimming pool was closed var z = function () { console.log(b, c); } // log: Output the beautified result, the function will directly print the function string // dir: direct directly output the original object, in order to see the body of the function console.dir(z) // scopes: scopes, array type // The scope used to store variables from other scopes used in the function body // In order to distinguish the type of scope: there are two token words // Global: represents the global scope, that is, the window object // Closure: Closure; represents function scope // -- This title represents a state of the function scope: bound by other functions // -- To save memory: keep only useful variables return z } var z = y() //Open the memory, generate b and c variables and store them here, and destroy them after execution z() // y() //Open the memory, generate b and c variables and store them here, and destroy them after execution // y() //Open the memory, generate b and c variables and store them here, and destroy them after execution // y() //Open the memory, generate b and c variables and store them here, and destroy them after execution // Functions have two states: static and dynamic function show() { } //Static: declared; parked in the garage after buying the car show() //Dynamic: after triggering; driving / // interview questions var a = 10 function x() { a = 20 } // If the function is not called, the code in it will not run // x() console.log(a) </script> </body> </html>
Seven, private
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>private variables 14:01</title> </head> <body> <!-- private: privately owned, Variables only belong to the function itself --> <script> // Example: Make a variable to record the number of x function calls // Approach 1 (mistake): Declare variable x in the function, resulting in the initialization of x every time the function is run // Method 2 (mistake): Declare variable x outside the function, causing other functions in the same scope to modify this x // Method 3 (correct): Declare x in an independent anonymous function scope to achieve privateness; then use the closure mechanism to bind x to the function for use // Anonymous function self-tuning: In order to quickly generate function scope, local scope var x = (function () { var n = 0 //Specific to anonymous function scope // The n in the function belongs to the anonymous function scope, so it will be bundled and stored in the scopes attribute // var x = function(){} // return x return function () { n++ console.log('Number of calls:', n); } // console.dir(x) // return x //Use the return value to expose to the outside world })() // var n = 0 // function x() { // n++ // console.log('Number of calls:', n); // } x() x() x() x() // practise: // Plugin tabout, use the tab key to move the cursor outside the brackets var y = (function () { // Private variables: belong to anonymous function scope var n = 0 // Use the closure mechanism to bind the anonymous function scope to the function and store it in its scopes attribute // Use return to expose to external use return function () { n++ console.log(n) } })() y() y() y() y() </script> </body> </html>
Eight, arguments
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>arguments 14:42</title> </head> <body> <!-- arguments: is an implicit keyword in the function, where all arguments received by the function are stored --> <script> // uname: known as the formal parameter -- should see the name function show(uname) { // It is very common that the number of formal parameters and actual parameters does not correspond console.log(arguments); } // Actual parameter -- the actual value received by the function show('bright', 35, '18784556898', true) / // Purpose: To make a function with an unfixed number of actual parameters var m = Math.max(12, 3, 4, 6, 7) console.log(m) var m = Math.max(12, 3, 4, 6, 7, 34, 456, 56, 76, 87) console.log(m) var m = Math.max(12, 3, 4, 6, 7, 43, 2) console.log(m) make function max() { console.log(arguments) var x = arguments[0] for (var i = 1; i < arguments.length; i++) { var value = arguments[i] // Syntactic sugar: The author provides some simplified grammars, which can be used when some fixed conditions are met // Simplify -> Lazy: Being lazy can make you happy!! Like eating sugar // If the if condition has only one line of code, {} can be omitted if (value > x) x = value } return x //return final result } // Programming thinking: Express human problem-solving thinking in code and let the computer execute it console.log(max(12, 33, 54, 65, 765)) console.log(max(12, 33, 54, 65, 765, 4, 345, 456, 756)) </script> </body> </html>
Nine, function overloading
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>function overloading 15:26</title> </head> <body> <!-- function overloading: Inside the function, it is different according to the number or type of actual parameters, load different logic code -- For making multifunction functions, Let one function do more than one job --> <script> // Double 11 needs a function to calculate product discount information function zheKou(money) { console.log(arguments); // 3 parameters if (arguments.length == 3) { var man = arguments[1] var jian = arguments[2] if (money >= man) money -= jian console.log('full discount:', money); } if (arguments.length == 2) { if (typeof arguments[1] == 'number') { money *= arguments[1] console.log('Discount paid:', money); } // vip's if (typeof arguments[1] == 'string') { // if (arguments[1] == 'vip1') money *= 0.9 // if (arguments[1] == 'vip2') money *= 0.8 // if (arguments[1] == 'vip3') money *= 0.7 var list = { vip1: 0.9, vip2: 0.8, vip3: 0.7 } // Stored in vip_n is the attribute name var vip_n = arguments[1] money *= list[vip_n] //Through the attribute name, find the number to be multiplied console.log('vip:', money); } } } // There are many ways to use zheKou(5000, 0.7) // 30% discount zheKou(5000, 0.5) // 50% off zheKou(5000, 3000, 600) //Full 3000 minus 600 zheKou(5000, 4000, 800) //Full 4000 minus 800 zheKou(5000, 'vip1') // 10% off zheKou(5000, 'vip2') // 20% off zheKou(5000, 'vip3') // 7% off </script> </body> </html>
10. Square bracket attribute syntax
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>attribute 15:51</title> </head> <body> <script> // There are two syntaxes for property names of objects: dot syntax and square bracket syntax var emp = { uname: "bright", age: 19 } // Dot syntax is suitable for directly writing attribute names console.log(emp.uname, emp.age) emp.phone = '10086' console.log(emp); // Square bracket syntax: suitable for scenarios where the value is a variable -- only common when encapsulating functions var x = 'ename', y = 'age' var emp1 = { // When the editor sees [], it will recognize that the code in it is JS code [x]: 'the bubble', [y]: '18', [2 + 6]: '999', ['ni' + 'it is good']: "Ha ha" } console.log(emp1); var z = 'ni it is good' console.log(emp1[z]); console.log(emp1.z)// The property name is the property of z </script> </body> </html>
11. Heavy load exercise
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Exercise 16:23</title> </head> <body> <!-- function overloading: It is to use the number or type of actual parameters to be different, perform different logical operations -- if combine arguments judge -- Implement multifunctional functions --> <script> // cumulative case var x = 0 for (var i = 1; i <= 100; i++) { x += i } function sum() { var x = 0 if (arguments.length == 1) { for (var i = 1; i <= arguments[0]; i++) { x += i } } if (arguments.length == 2) { for (var i = arguments[0]; i <= arguments[1]; i++) { x += i } } if (arguments.length == 3) { for (var i = arguments[0]; i <= arguments[1]; i += arguments[2]) { x += i } } console.log(x) } // Target effect: Make a function that can get the sum of digital accumulation sum(100) // Get 1 + 2 + 3 + .... + 100 sum(200) // 1 + .. + 200 sum(50, 200) // Get 50 + 51 + ... + 200 sum(11, 44) // 11 + .. + 44 sum(100, 200, 10) //Get 100 + 110 + 120 + ... + 200 </script> </body> </html>
Twelve, this
- Method 1: The function is fixed, and the value is passed into the function as an actual parameter in turn, and the execution
- Method 2: door-to-door service -- the function directly enters the internal execution of the value
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>this 16:50</title> </head> <body> <!-- this: this -- what does it represent, depends on the context After the function has this keyword, provides another usage -- Put the function into the object to execute --> <script> // Save the width and height of the rectangle var r1 = { width: 100, height: 50 } var r2 = { width: 1, height: 4 } function area2() { // this: This -- represents the object where the function runs console.log('this:', this); return this.width * this.height } r2.area2 = area2 var y = r2.area2() console.log(y) // Function door-to-door service r1.area2 = area2 // stored in the r1 object var x = r1.area2() // Triggered by the r1 object -- activate console.log(x) // Calculate the area function area(r) { return r.width * r.height } // Pass the value into the function for processing console.log(area(r1)) </script> </body> </html>
Summarize
- statement boost
- Intelligent bill of JS engine -- there is a set of rules inside, which will automatically modify non-standard codes to standard codes, and then execute them (the best solution: do not write non-standard codes)
- Irregularity: If the type of the value participating in the operation in the expression is incorrect, it will be automatically type converted (which type of conversion rule will be applied in which scene -- need to remember)
- statement operation
- Specification requirements: must be declared first, then used
- Once your code is not standardized, it will trigger an invisible declaration promotion operation, and promote all declaration operations to the top of the code
- Hosting environment: In what environment does JS run, you can use the api in this environment - Skills
- node.js: handle server-related APIs
- Browser: deal with browser-related, stored in the window object
- scope
- global:
- Local: temporarily generated when the function is executed
- Avoid Global Pollution:
- Using anonymous function self-invocation to generate function scope, declaring variables in this scope will not pollute the global
- Closure:
- The function uses variables from other functions, in order to prevent its release and make itself unusable
- So: keep it in its own scopes property -- bind
- This hijacked function scope is in a closed state
- Privatization:
- Use the closure feature to get private scope variables
- Scope chain:
- When variables are used in a function, they will be found and used from the nearest scope
- arguments:
- The implicit attribute in the function, which saves all the actual parameters
- Make a function with an unfixed number of actual parameters -- find the maximum value
- Function Overloading: Multifunction Functions
- this:
- This; represents the object where the function runs
- This keyword gives the function the ability to enter the object to run