In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "the collation and summary of the basic knowledge of the front end". In the daily operation, I believe that many people have doubts about the arrangement and summary of the basic knowledge of the front end. The editor consulted all kinds of materials and sorted out the simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about the arrangement and summary of the basic knowledge of the front end. Next, please follow the editor to study!
The life cycle of a HTML page
There are three important events in the life cycle of a HTML page:
DOMContentLoaded-- the browser has fully loaded the HTML,DOM tree and built it, but it looks like
Without defer or async, all elements are parsed in the order in which they appear on the page, and the browser immediately loads and executes the specified script, and the subsequent code is parsed only after parsing the contents of the previous script element.
The async and defer attributes work only on external scripts and are automatically ignored when src does not exist.
Two ways to use
1. To embed script code in the page, simply specify the type attribute
Function sayHi () {console.log ('hihihi'); / / the' string cannot appear internally. If it must be present, you must use the escape label'\ 'alert ('');}
The code contained in the element is interpreted from top to bottom, and the rest of the page will not be loaded or displayed by the browser until the interpreter has evaluated all the code within the element.
two。 To include external js files, the src attribute is required.
/ / elements with the src attribute should not contain extra js code between tags. Even if they do, only external files will be downloaded and executed, and internal code will be ignored.
Like embedded js code, page processing stops temporarily when parsing an external js file.
Ways to change the behavior of scripts
1. Defer: download immediately, delay execution
The process of loading and rendering subsequent document elements will occur in parallel (asynchronously) with the loading of the script, but the script will be executed after all the elements have been parsed. Scripts are always executed in declarative order.
Executes before the DOMContentLoaded event.
2. Async: asynchronous script
The process of loading and rendering subsequent document elements occurs in parallel (asynchronously) with the loading and execution of the script. However, the execution of async after the download is complete will block the parsing of HTML. Scripts are executed as soon as they are loaded, and there is no guarantee that asynchronous scripts will be executed in the order in which they appear on the page.
It must be executed before the load event, possibly before or after the DOMContentLoaded event.
Difference:
Meta
The META tag is a key tag in the HEAD area of the HTML tag. Although the information provided by the tag is invisible to the user, it is the most basic meta-information of the document. In addition to providing document character sets, languages, authors and other web page-related information, you can also set information to search engines for the purpose of SEO (search engine Optimization).
The HTML element represents any metadata information that cannot be represented by one of the other HTML meta-related (meta-related) elements (, or).
Attribute
Name
Sets the name of the metadata. The name and content attributes can be used together to provide metadata to the document as a name-value pair, with content as the value of the metadata.
Content
Sets meta information related to the http-equiv or name property.
Charset
Declares the character encoding of the document. If this property is used, its value must be "utf-8" independent of ASCII case (ASCII case-insensitive).
Http-equiv
A compilation instruction is defined, which acts like the http protocol, telling the browser some information about character settings, page refresh, cookie, cache and so on. The attribute is called http-equiv because all allowed values are the names of the HTTP headers. The values that can be set are:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Content-security-policy: it allows the page author to define the content policy for the current page. The content policy mainly specifies allowed server sources and scripting endpoints, which helps prevent cross-site scripting attacks.
Expires: can be used to set the expiration time of a web page. Once it expires, it must be called again on the server. Content must use GMT time format
Content-type: if you use this property, its value must be "text/html; charset=utf-8". Note: this attribute can only be used for documents whose MIME type is text/html, not for documents with a MIME type of XML.
Default-style: sets the name of the default CSS stylesheet group.
Refresh: regularly refresh or jump the web page within a specified time n
If the content contains only one positive integer, the page refreshes after n seconds.
If content contains a positive integer followed by the string'; url=' and a legal URL, it is the interval (in seconds) that you redirect to the specified link.
The types of metadata defined by the meta element include the following:
If the name attribute is set, the meta element provides document-level (document-level) metadata that is applied to the entire page.
If the http-equiv attribute is set, the meta element is a compilation instruction that provides the same information as a similarly named HTTP header.
If the charset attribute is set, the meta element is a character set declaration that tells the document what kind of character encoding to use.
If the itemprop attribute is set, the meta element provides user-defined metadata.
Note: the global attribute name has special semantics in the element; in addition, the itemprop attribute cannot be used when any of the three attributes name, http-equiv, or charset exist in the same tag.
Use
There are multiple attributes in the content value, separated, and multiple properties are set at the same time.
/ * name * / / adapt to mobile devices / / check html format: disable converting digits to dial-up links / * charset * / / * http-equiv * /
Meta viewport meta-information
What is viewport?
Viewport is the visual area of the browser, and the size of the visual area is set by the browser itself. It may be larger or smaller than the visual area of the mobile device. Generally speaking, the viewport on the mobile device is larger than the visual area of the mobile device. View the Viewport size in the console output window.innerWidth.
Related concepts
Device Pixel: device screen resolution. The resolution of iphone6p is 1334 to 750.
Device independent pixel: the "dots" used by the program on the device to depict the data, which are viewed in the console with screen.width/height. The device independent pixel of iphone6p is 375mm 667.
Device pixel ratio (DPR): device pixel (width) / device independent pixel (width). The higher the DPR, the more refined the rendering. Output window.devicePixelRatio in the console to view the pixel ratio of the device. The device pixel ratio of iphone6s is 750 / 375 = 2.
CSS pixel: a unit used by a browser to accurately measure content on a web page. In general (the page zoom ratio is 1), 1 CSS pixel is equal to 1 device independent pixel.
Screen size: the length of the diagonal of the screen, in feet.
Pixel density (PPI): the number of pixels per inch screen.
Why use meta viewport?
Typically, browsers on mobile devices set viewport to 980px or 1024px, and the page will scroll horizontally because the width of the visual area of the mobile device is smaller than the width of the default viewport. So there is a meta tag to set the viewport primitive for mobile web page optimization.
Meta viewport attribute
Width: controls the size of the viewport, which can be assigned a value (a positive integer) or a special value (for example, device-width device independent pixel width, when the unit is scaled to 1)
Initial-scale: the initial scale, that is, the scale when the page is loaded for the first time, is a number (can be decimal)
Maximum-scale: the maximum scale to which users are allowed to zoom, which is a number (can be decimal)
Minimum-scale: the minimum scale to which users are allowed to zoom, which is a number (can be decimal)
User-scalable: whether users are allowed to zoom manually, with a value of "no" (not allowed) or "yes" (allowed)
Height: corresponds to width (rarely used).
Basic types and reference types
Basic type
Basic types: undefined, null, string, number, boolean, symbol
Characteristics
1. The value of the basic type is immutable
/ / No method can change the value of a basic type let name = 'jay'; name.toUpperCase (); / / output' JAY' console.log (name); / / output 'jay'
two。 The comparison of basic types is the comparison of values.
/ / only when their values are equal are they equal let a = 1; let b = true; console.log (a = = b); / / true / / some type conversions are made when comparing two different types of variables. / / convert true to the number 1 and then compare it with the number 1, and the result is true.
3. Basic types of variables are stored in the stack area (stack area refers to stack memory in memory)
Reference type
Reference types: Object, Array, RegExp, Date, Function, etc.
The reference type can also be called an object. An object is a collection of properties and methods, that is, reference types can have properties and methods, and properties can contain basic types and reference types.
Characteristics
1. The value of the reference type is variable
/ / We can add properties and methods to the reference type, or delete their properties and methods let person = {name: 'pig'}; person.age = 22; person.sayName = () = > console.log (person.name); person.sayName (); / /' pig' delete person.name
two。 The comparison of reference types is the comparison of references.
Let person1 ='{}'; let person2 ='{}'; console.log (person1 = = person2); / / string values are the same, true let person1 = {}; let person2 = {}; console.log (person1 = = person2); / / two objects have different addresses in heap memory, false
3. The value of the reference type is an object that is saved in both stack memory and heap memory
Unlike other languages, javascript does not allow direct access to locations in memory, that is, it cannot directly manipulate the memory space of objects. In fact, it is a reference to an Operand, so the value of the reference type is accessed by reference. To be exact, the storage of the reference type requires the joint completion of the stack area and the heap area of memory (the heap area refers to the heap memory in memory). The stack area holds the variable identifier and the pointer to the object in the heap memory. it can also be said to be the address of the object in heap memory.
Scope and execution context
The whole execution process of JavaScript code is divided into two stages, the code compilation phase and the code execution phase.
Compilation phase: completed by the compiler, translating the code into executable code. At this stage, the scope rules are determined.
Execution phase: completed by the engine, the main task is to execute executable code. The execution context is created at this stage.
Scope
To put it simply, a scope is a region with no variables. Scopes can be nested. The scope specifies how to find the variable, that is, to determine the currently executing code's access to the variable. The scope is determined when the function is defined, not by the function call.
Before ES6, JavaScript only had global scope and function scope. After ES6, the block-level scope (the most recent scope of curly braces) has been added, variables declared through let and const.
The scope actually consists of two parts:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Something that records variable information in scope (hypothetical variables, constants, functions, etc., collectively referred to as variables) and code structure information is called Environment Record.
A reference _ _ outer__, this reference points to the parent scope of the current scope. The _ _ outer__ of the global scope is null.
Lexical scope
JavaScript uses lexical scope (lexical scoping), that is, static scope.
The so-called lexical (code) scope is the scope of the code reflected in the process of writing. Once the code is written, the scope has been determined before it is run (without execution). This is the so-called lexical scope.
The rules of lexical scope:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Function allows access to data outside the function
In the whole code structure, only functions can be scoped.
The function rule is first analyzed by using the variable promotion rule.
If the name is in the current action rule, the outer name is not considered.
Var a = 1; function out () {var a = 2; inner ();} function inner () {console.log (a)} out (); / / = > 1
Domain chain
When looking for a variable, it will first look for it from the variable object of the current context. If it is not found, it will look for it from the variable object of the execution context of the parent (the parent at the lexical level), and always find the variable object of the global context, that is, the global object. In this way, a pointer list consisting of multiple variable objects in the execution context is called a scope chain.
The scope chain is essentially a list of pointers to a series of variable objects in the current environment and the upper environment (it only references but does not actually contain variable objects). The scope chain ensures that the current execution environment has orderly access to variables and functions that meet the access rights.
Example:
An array scopeChain is used to represent the scope chain, the first term scopeChain [0] of the array is the front end of the scope chain, and the last item of the array is the end of the scope chain, and all the ends are global variable objects.
Var a = 1; function out () {var b = 2; function inner () {var c = 3; console.log (a + b + c);} inner ();} out ()
First, the global context is created when the code starts running, then the execution context of the out function is created when running to out (), and finally the execution context of the inner function is created when running to inner (). We set their variable objects to VO (global), VO (out), and VO (inner), respectively.
When the function is created, the execution context is:
/ / Global context globalEC = {VO: {out:, / / indicates the address reference of out a: undefined}, scopeChain: [VO (global)], / / scope chain} / / execution context of out function outEC = {VO: {arguments: {...}, inner:, / / indicates the address reference b: undefined} of inner, scopeChain: [VO (out) VO (global)], / / scope chain} / / execution context of the inner function innerEC = {VO: {arguments: {...}, c: undefined,}, scopeChain: [VO (inner), VO (out), VO (global)], / / scope chain}
Execution context
To put it simply, preparations are made when a function is executed during code execution, and the "preparatory work" here is called "execution context" (EC), also known as execution context, also known as execution environment. The js engine creates an execution context stack (Execution context stack,ECS) to manage the execution context.
When a function is called, a new execution context is created. The life cycle of an execution context can be divided into two phases:
Creation phase: at this stage, the execution context creates variable objects, establishes scope chains, and determines the direction of the this.
Code execution phase: begins to execute the code, completing variable assignments, function references, and other code execution.
Characteristics
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
There is only one execution context that is active, and only the context at the top of the stack is active, executing the code in it.
Each time the function is called, a new execution context is created.
The global context is created when the code starts execution, only one, always at the bottom of the stack, when the browser window closes.
Creates a context when the function is called.
Variable object
The process of creating variable objects
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Create an arguments object. Check the parameters in the current context and establish the properties and property values under the object.
Check the function declaration of the current context, that is, the function declared using the function keyword. Create a property in the variable object with the name of the function, and the value of the property is a reference to the memory address where the function is located. If the property of the function name already exists, the property will be overwritten by the new reference.
Check the variable declaration in the current context, and each time a variable declaration is found, a property is established in the variable object with the variable name, and the attribute value is undefined. If the attribute of the variable name already exists, in order to prevent the function with the same name from being modified to undefined, it will be skipped directly and the original property value will not be modified.
Active object
The variable object and the active object are actually the same object, only in different lifecycles of the execution context. However, only variable objects in the execution context at the top of the function call stack become active objects.
Execute context stack
The execution context can be understood as the execution environment of the current code, and the runtime environment in JavaScript probably includes three situations:
Global environment: JavaScript code will enter this environment first when it runs
Function environment: when a function is called for execution, it will enter the current function to execute code
Eval
When the code starts to execute, it will first generate a global execution context. When a function is called, it will generate a function execution context. After the function call is completed, its execution context and its data will be destroyed, return to the global execution environment, and the global execution environment will be destroyed after the web page is closed. In fact, this is a process of pushing the stack off the stack, the global context is always at the bottom of the stack, and the currently executing function context is at the top of the stack.
Var a = 1; / / 1. Enter the global context function out () {var b = 2; function inner () {var c = 3; console.log (a + b + c);} inner (); / / 3. Enter the inner function context} out (); / / 2. Enter the out function context
The execution of the above code goes through the following process:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
When the code starts to execute, the global execution context is created, and the global context is stacked.
After the global context is put into the stack, the code starts to execute, such as assignment, function call and so on. When it is executed to out (), the activation function out creates its own execution context, and the out function context enters the stack.
After the out function context is put into the stack, the code in it starts to execute, such as assignment, function call and so on. When executing to inner (), the activation function inner creates its own execution context, and the inner function context enters the stack.
After the inner function context is put into the stack, the code starts to execute, such as assignment, function call, printing and so on. Because there is no need to generate other execution context, after all the code is executed, the inner function context is off the stack.
The inner function context goes out of the stack and goes back to the out function execution context, and then executes the rest of the code in the out function. Since there is no need to generate other execution contexts, after all the code is executed, the out function context is off the stack.
After the out function context is unstacked, it returns to the global execution context until the browser window closes and the global context is unstacked.
The difference between scope and execution context
The scope is just a "territory" where there are no variables. Variables are implemented through variable objects in the execution context corresponding to the scope. So the scope is static while the execution context is dynamic. When there are closures, there are two contexts in one scope.
Under the same scope, different calls to the same function will produce different execution contexts, and then produce different values of variables, so the values of variables in the scope are determined during execution, and the scope is determined when the function is created.
If you want to find the value of a variable under a scope, you need to find the execution context corresponding to that scope, and then find the value of the variable in it.
Variable lifting
In Javascript, the declaration of functions and variables will be promoted to the top of the function, only the declaration of variables will be promoted, and the assignment of variables will not be promoted. Function declaration is different from variable declaration, function expression and variable expression only their declaration is promoted, function declaration is function declaration and implementation are promoted.
Function foo () {console.log ("global foo");} function bar () {console.log ("global bar");} / / define the global variable var v = "global var"; function hoistMe () {/ / var bar; is promoted to the top and does not implement / / var v; console.log (typeof foo); / / function console.log (typeof bar) Functions and variables with the same name are defined in the / / undefined console.log (v) / / undefined / / function, and will be promoted to the top of the function no matter where they are defined. Foo (); / / local foo bar (); / / error, TypeError "bar is not a function" / / function declaration, variable foo and its implementation are promoted to the top of the hoistMe function function foo () {alert ("local foo") } / / function expression, only the variable bar is promoted to the top of the function, and the implementation is not promoted var bar = function () {alert ("local bar");}; / / define the local variable var v = "local";}
Let variable promotion
Console.log (a); / / Uncaught ReferenceError: an is not defined let a = "I am a"; let b = "I am outside B"; if (true) {console.log (b); / / Uncaught ReferenceError: b is not defined let b = "I am inside B";}
If b has no variable promotion, it should output b in the global scope instead of an error when executing to console.log.
We can infer that there is indeed a variable promotion here, and the reason why we cannot access it is actually because of the dead zone design of let: the part from the top of the current scope to the middle of the variable declaration position is the dead zone of the let variable, and access to the variable is prohibited in the dead zone. From this, we conclude that there is a variable promotion in the variable declared by let, but we cannot access the variable before declaring it because of the dead zone.
Var let distinction
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
A variable declared by var for which only a function can create a new scope
A variable declared by let that supports block-level scope for which curly braces can create a new scope
In the same scope, var can repeatedly declare variables with the same identifier, while let does not allow it
Variables declared by let prohibit access before declaration
/ / Global variable var I = 0; / / define external function function outer () {/ / access global variable console.log (I); / 0 function inner1 () {console.log (I); / / 0} function inner2 () {console.log (I); / / undefined var i = 1; console.log (I) / / 1} inner1 (); inner2 (); console.log (I); / / 0}
Closure
A closure is a function that has access to variables in the scope of another function.
Official explanation: a closure is a combination of a function and the lexical environment in which it was created. This environment contains all the local variables that can be accessed when the closure is created. (lexical scope)
Popular explanation: the key to a closure is that its variable object should have been destroyed after an external function call, but the existence of the closure allows us to still access the variable object of the external function.
When a function is deactivated, an execution environment and the corresponding scope chain are created. The active object of the function is then initialized with the values of arguments and other named parameters. However, in the scope chain, the active object of the external function is always in the second place, and the active object of the external function is in the third place. Up to the global execution environment as the end of the scope chain.
The scope chain is essentially a list of pointers to variable objects that only reference but do not actually contain variable objects.
Whenever a variable is accessed in a function, a variable with the same name is searched from the scope chain. Generally speaking, when the function is executed, the locally active object is destroyed, and only all scoped active objects are stored in memory. However, closures are different.
Create closure: create a function inside another function
The scope chain of the function add () {let a = 1; let b = 3; function closure () {bounded closure; return a + b;} return closure;} / / closure contains its own scope, as well as the scope and global scope of the function that contains it.
Life cycle
Typically, the scope of a function and all its variables are destroyed at the end of the function execution. However, after you create a closure, the scope of the function is saved until the closure does not exist.
When the function closure in the closure returns from add, its scope chain is initialized to the active object and global variable object that contains the add function. This allows closure to access all the variables defined in add.
More importantly, the add function will not be destroyed after it is executed, because the scope chain of the closure function is still referencing the active object.
In other words, when the add returns, the scope chain of its execution environment is destroyed, but its active object remains in memory until the closure is destroyed.
Function add (x) {function closure (y) {return x + y;} return closure;} let add2 = add (2); let add5 = add (5); / / add2 and add5 share the same function definition, but different environments are saved / / in the add2 environment, x is 5. In add5, x is 10 console.log (add2 (3)); / 5 console.log (add5 (10)); / / 15 / / release the reference to the closure add2 = null; add5 = null
This objects in closures
Var name = 'window'; var obj = {name:' object', getName: () = > {return () = > {return this.name;} console.log (obj.getName () ()); / / window
Obj.getName () () calls an anonymous function in the global scope, and this points to window.
The function name is separated from the function function, so don't think that the this inside the function points to wherever the function is.
Window is the environment in which anonymous function functions are executed.
Pay attention to use
1) because the closure will keep all the variables in the function in memory, which consumes a lot of memory, the closure should not be abused, otherwise it will cause performance problems on the web page and may cause memory leakage in IE. The solution is to delete all unused local variables before exiting the function.
2) the closure will change the value of the internal variable of the parent function outside the parent function. So, if you use the parent function as an object (object), the closure as its common method (Public Method), and the internal variable as its private property (private value), you must be careful not to change the value of the internal variable of the parent function.
Use
Mimic block-level scope
Private variable
Module mode
Creating closures in loops: a common mistake
Function show (I) {console.log (I);} function showCallback (I) {return () = > {show (I);};} / Test 1 [3Jing 3] const testFunc1 = () = > {/ / var i; for (var I = 0; I)
< 3; i++) { setTimeout(() =>Show (I), 300);}} / / Test 2 [0d1 var 2] const testFunc2 = () = > {for (var I = 0; I)
< 3; i++) { setTimeout(showCallback(i), 300); } } // 测试3【0,1, 2】 闭包,立即执行函数 // 在闭包函数内部形成了局部作用域,每循环一次,形成一个自己的局部作用域 const testFunc3 = () =>{for (var I = 0; I)
< 3; i++) { (() =>{setTimeout (() = > show (I), 300);}) (I);}} / / Test 4 [0L1, 2] let const testFunc4 = () = > {for (let I = 0; I)
< 3; i++) { setTimeout(() =>Show (I), 300);}
The callback of the setTimeout () function is an asynchronous task, which appears in the macro task queue and is pressed to the end of the task queue. It will not be its turn until this code is supposed to be a for loop, which is a synchronous task.
Test 1 error reason: the value assigned to setTimeout is a closure. These closures are made up of their function definitions and the environment captured in the testFunc1 scope. These three closures are created in a loop, but they share the same lexical scope in which there is a variable I. This is because the variable I is declared using var and has a functional scope because the variable is promoted. When the callback of onfocus is executed, the value of I is determined. Since the loop is executed long before the event is triggered, the variable object I (shared by the three closures) has pointed to the last value of I.
Test 2 correct reason: all callbacks no longer share the same environment, and the showCallback function creates a new lexical environment for each callback. In these environments, I points to the corresponding subscript in the array.
Test 4 correct reason: the for loop body in JS is relatively special, each execution is a new independent block scope, after the variables declared by let are introduced into the scope of the for loop body, it will not change and will not be affected by the outside world.
This pointing to the problem
This is a pointer to the object on which we call the function.
Execution context: is a concept in the language specification, which, in popular words, is roughly equivalent to the "environment" of function execution. Specifically, variable scopes (and scope chains, variables from external scopes in closures), function parameters, and values of this objects.
Find out the direction of this
The value of this is not determined by which object the function definition is placed in, but by who evokes the decision when the function is executed.
Var name = "Jay Global"; var person = {name: 'Jay Person', details: {name:' Jay Details', print: function () {return this.name;}}, print: function () {return this.name;}}; console.log (person.details.print ()) / / [print] Jay Details console.log called by details object (person.print ()); / / [print called by person object] Jay Person var name1 = person.print; var name2 = person.details; console.log (name1 ()); / / [name1 has no calling object before, so it is window] Jay Global console.log (name2.print ()) / / [print] Jay Details called by name2 object
This and arrowhead functions
The arrow function binds its context by lexical scope, so the this actually refers to the original context. The arrow function keeps the lexical scope of its current execution context unchanged, while the ordinary function does not. In other words, the arrow function inherits the value of this from the lexical scope that contains it.
Anonymous function, which is not called as a method of an object, so the this keyword points to the global window object
Var object = {data: [1je 2jue 3], dataDouble: [1je 2je 3], double: function () {console.log (this); / / object return this.data.map (function (item) {/ / this is the double console.log (this) of the current object,object call / / the anonymous function passed to map () has not been called by any object, so it is window return item * 2;});}, doubleArrow: function () {console.log (this); / / object return this.dataDouble.map (item = > {/ / this is the doubleArrow console.log (this) of the current object,object call / / doubleArrow is called by object, which is the context, so it is window return item * 2;});}}; object.double (); object.doubleArrow ()
Explicitly set the execution context
Developers can directly manipulate the execution context in JavaScript by using built-in features. These features include:
Bind (): you don't need to execute a function to set the value of this to an object of your choice. Pass multiple parameters separated by commas. The function will not be executed immediately after setting the this keyword.
Apply (): set the value of this exactly to an object of your choice. Apply (thisObj, argArray) takes two parameters, thisObj is the this where the function runs, argArray is the parameter array, and each item in the array is the parameter you want to pass to the function. If none of the parameters argArray and thisObj are provided, the Global object is used as a thisObj. Finally, the function is executed immediately.
Call (): set the value of this exactly to an object of your choice. Then, like bind, multiple arguments are passed to the function separated by commas. Syntax: call (thisObj,arg1,arg2,..., argn); if no thisObj parameter is provided, then the Global object is used for thisObj. Finally, the function is executed immediately.
This and bind
Var bobObj = {name: "Bob"}; function print () {return this.name;} var printNameBob = print.bind (bobObj); console.log (printNameBob ()); / / Bob
This and call
Function add (a, b) {return a + b;} function sum () {return Array.prototype.reduce.call (arguments, add);} console.log (sum
This and apply
Apply is to accept an array version of call.
Math.min; / return 1 Math.min; / / return NaN. Only accept digital Math.min.apply (null, [1Power2jing3jin4]); / / return 1 function Person (name, age) {this.name = name; this.age = age;} function Student (name, age, grade) {Person.apply (this, arguments); / / Person.call (this, name, age); this.grade = grade;} var student = new Student ("sansan", 21, "first grade") Console.log ("student:", student); / / {name: 'sansan'; age:' 21 years, grade: 'Grade one'}
If your parameters already exist in an array, naturally use apply, and if the parameters are scattered and not related to each other, use call.
Object attribute type
Data attribute
The data property contains a location of the data value where the value can be read and written, and the data property has four properties that describe its behavior:
Configurable: indicates whether the property is deleted through delete to redefine the property, whether the property of the property can be modified, or whether the property can be changed to an accessor property. The default value is true
Enumerable: indicates whether the property can be returned through the for-in loop. The default value is true
Writable: indicates whether the attribute can be modified. The default value is true
Value: contains the data value of this attribute. The default value is true
Accessor properties
Functional programming
Functional programming is a programming paradigm and a style of constructing computer program structures and elements. it regards calculation as the evaluation of mathematical functions and avoids the change of state and the change of data.
Pure function
Pure functions are stable, consistent and predictable. Given the same parameters, pure functions always return the same result.
Characteristics
1. If the same parameters are given, the same results will be obtained.
We want to implement a function that calculates the area of a circle.
Not pure functions do this:
Let PI = 3.14; const calculateArea = (radius) = > radius * radius * PI; / / it uses a global object calculateArea (10) that is not passed as an argument to the function; / / returns 314.0
Pure function:
Let PI = 3.14; const calculateArea = (radius, pi) = > radius * radius * pi; / / now pass the value of PI as an argument to the function so that no external objects are introduced. CalculateArea (10, PI); / / returns 314.0
two。 No obvious side effects
Pure functions do not cause any observable side effects. Examples of visible side effects include modifying global objects or parameters passed by reference.
Now, implement a function that receives an integer and returns a 1 operation on that integer and returns:
Let counter = 1; function increaseCounter (value) {counter = value + 1;} increaseCounter (counter); console.log (counter); / / 2
The impure function receives the value and reassigns the counter to increase its value by 1.
Functional programming discourages variability (modifying global objects).
Let counter = 1; const increaseCounter = (value) = > value + 1; / / the function returns an incremental value without changing the value of the variable increaseCounter (counter); / / 2 console.log (counter); / / 1
3. Reference transparency
If a function always produces the same result for the same input, it can be considered transparent.
Implement a square function:
Const square = (n) = > n * n; square (2); / / 4 passing 2 as an argument to the square function always returns 4
You can change square (2) to 4, and our function is reference transparent.
Pure function use
Unit testing
Pure functional code is certainly easier to test and doesn't require mock anything. So we can unit test pure functions in different contexts.
A simple example is to receive a set of numbers and add 1 to each number:
Let list = [1,2,3,4,5]; const incrementNumbers = (list) = > list.map (number = > number + 1); incrementNumbers (list); / / [2,3,4,5,6]
For the input [1, 2, 3, 4, 5, and 5], the expected output is [2, 2, 3, 4, 4, 5, and 5].
Pure functions can also be regarded as values and used as data.
Reference it from constants and variables.
Pass it as an argument to other functions.
Return it as a result of other functions.
The idea is to treat the function as a value and pass the function as data. In this way, we can combine different functions to create new functions with new behavior.
Suppose we have a function that sums two values and then doubles the value, as follows:
Const doubleSum = (a, b) = > (a + b) * 2
Subtract the two values, and then double the value:
Const doubleSubtraction = (a, b) = > (a-b) * 2
These functions have similar logic, but the difference lies in the function of the operator. If we can treat functions as values and pass them as parameters, we can build a function that receives the operator function and uses it inside the function.
Const sum = (a, b) = > a + b; const subtraction = (a, b) = > a-b; const doubleOperator = (f, a, b) = > f (a, b) * 2; doubleOperator (sum, 3,1); / / 8 doubleOperator (subtraction, 3,1); / / 4
Promise
Promise must be one of the following three states: waiting state (Pending), executive state (Fulfilled) and rejected state (Rejected). Once the Promise is resolve or reject, it can no longer be migrated to any other state (that is, state immutable).
Basic process:
Initialize Promise state (pending)
Execute then (..) Register the callback processing array (the then method can be called multiple times by the same promise)
Immediately execute the fn function passed in Promise, pass the resolve and reject functions inside Promise to fn as parameters, and deal with them according to the event mechanism timing.
In Promise, it is guaranteed that the parameters onFulfilled and onRejected passed in by the then method must be executed in the new execution stack after the event loop in which the then method was called.
The real chain Promise means that after the current promise reaches the fulfilled state, it starts to proceed to the next promise.
Cross-domain
Because the same origin policy of the browser leads to cross-domain. The same origin policy is an important security policy, which is used to restrict how an origin document or its loaded script can interact with another source's resources. It can help block malicious documents and reduce the number of media that may be attacked.
The so-called homology means that "protocol + domain name + port" are the same. Different protocols, different domain names, and different ports will constitute cross-domain.
Cross-domain solution
1. Jsonp: server is required to cooperate with a callback function
2. CORS: server is required to set header: Access-Control-Allow-Origin
3. Window.name + iframe: the target server is required to respond to window.name.
4. Document.domain: only cross-domain application scenarios with the same primary domain but different sub-domains.
5. PostMessage + iframe of html5: you need to write a postMessage on the server or target page, mainly focusing on front-end communication.
6. Nginx reverse proxy: without server cooperation, you need to build a transit nginx server to forward requests.
Jsonp cross-domain
In HTML tags, there are no cross-domain restrictions on tags that acquire resources, such as script and img. Through the dynamic creation of script, and then request a reference URL to achieve cross-domain communication.
It needs to be used together with the front and rear ends. Generally, callback is set at the backend, and a callback is passed from the frontend to the backend API.
Only one get request can be implemented.
Chestnut
Front-end code:
Var script = document.createElement ('script'); script.type =' text/javascript'; / / pass a callback function name to the backend to facilitate the execution of the callback function script.src = 'http://xxxxxxx:8080/login?callback=handleCallback'; document.head.appendChild (script) defined in the front end when the backend returns; function handleCallback (res) {alert (JSON.stringify (res));}
Background code:
CORS-Cross-domain resource sharing
CORS is a W3C standard, the full name is "cross-domain resource sharing" (Cross-origin resource sharing).
CORS has two kinds of requests, simple requests and non-simple requests. It is a simple request as long as the following two conditions are met at the same time.
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
The request method is one of three methods: HEAD,GET,POST
The header information of HTTP does not exceed the following fields: Accept,Accept-Language,Content-Language,Last-Event-ID,Content-Type [limited to three values application/x-www-form-urlencoded, multipart/form-data, text/plain], and there is no custom HTTP header.
Simple request
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Browser: populate the domain where the client script is located into the Origin header and request resources from servers in other domains.
Server: according to the resource permission configuration, add Access-Control-Allow-Origin Header to the response header and return the result.
Browser: compare the Access-Control-Allow-Origin Header returned by the server with the Origin of the requested domain. If the current domain is authorized, the result is returned to the page. Otherwise, the browser ignores this response.
Web page: receive a result or an error prompt from the browser.
For simple cross-domain requests, browsers allow cross-domain requests as long as the Access-Control-Allow-Origin Header set by the server matches the source of the request. The `Access-Control-Allow-Methods and Access-Control-Allow-Headers set on the server side have no effect on simple cross-domain.
Non-simple request
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Browser: first send an OPTIONS pre-check request to the server to check whether the server supports real requests for cross-domain resource access. The browser will automatically add Origin Header, Access-Control-Request-Method Header and Access-Control-Request-Headers Header when sending OPTIONS requests.
Server: in response to the OPTIONS request, the Access-Control-Allow-Methods head is added to the responseHead. The value of method is the default value given by the server, and different servers may add different values. Access-Control-Allow-Origin Header and Access-Control-Allow-Headers Header are also added to the server. This depends on how the server responds to OPTIONS requests. If the server's OPTIONS response does not meet your requirements, you can manually configure the OPTIONS response on the server to respond to cross-domain requests with pre-checks. When configuring the response of the server OPTIONS, you can add an Access-Control-Max-Age head to tell the browser that there is no need to send a pre-check request again within a certain period of time, but it will not work if the browser disables caching.
Browser: when you receive the response from OPTIONS, compare whether the method of the real request belongs to one of the values of the returned Access-Control-Allow-Methods head, and origin, head will also compare whether it matches. If passed, the browser continues to send real requests to the server, otherwise a pre-check error will be reported: the source of the request is not allowed by the options response, the request method is not allowed by the options response, or a custom header in the request is not allowed by the options response.
Server: in response to the real request, put Access-Control-Allow-Origin Header, Access-Control-Allow-Methods and Access-Control-Allow-Headers Header in the response header to represent the domain, request method and request header that allow cross-domain resource requests, and return data.
Browser: accepts the result returned by the server to the real request and returns it to the web page
Web page: receive a result or an error prompt from the browser.
Access-Control-Allow-Origin is useful in both responding to options requests and responding to real requests, both of which must contain sources to be cross-domain. Access-Control-Allow-Methods and Access-Control-Allow-Headers are useful only when responding to options requests.
Carry cookie
In CORS cross-domain, browsers do not automatically send Cookie. For ordinary cross-domain requests, you only need to set it on the server side, while both the front and back end of the cross-domain request with cookie need to be set.
Browser, for cross-domain requests, you need to set the withCredentials property to true. Access-Control-Allow-Credentials: true must be included in the server's response.
In addition to Access-Control-Allow-Credentials, sending Cookie across domains also requires that Access-Control-Allow-Origin does not allow the use of wildcards. Otherwise, the browser will throw a The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard' * 'error. In fact, not only wildcards are not allowed, but only a single domain name can be specified.
Calculate Access-Control-Allow-Origin
Since Access-Control-Allow-Origin only allows a single domain name, the server may need to maintain a list of Origin that accepts Cookie, validate the Origin request header field and set it directly to the value of Access-Control-Allow-Origin. After the CORS request is redirected, the Origin header field is set to null, and you can choose to calculate the Origin from the Referer header field.
Concrete realization
Server-side response header configuration
Access-Control-Allow-Origin can be set to *, which means that data can be shared with any domain.
/ / set the server to accept cross-domain domain name "Access-Control-Allow-Origin": "http://127.0.0.1:8080", / / set the server to accept cross-domain request method 'Access-Control-Allow-Methods':' OPTIONS,HEAD,DELETE,GET,PUT,POST', / / set the server to accept cross-domain headers' Access-Control-Allow-Headers': 'x-requested-with, accept, origin, content-type' / / set the server not to pre-check the request time 'Access-Control-Max-Age': 10000 again, / / set the server to accept cross-domain Cookie' Access-Control-Allow-Credentials': true
Document.domain
This scheme is limited to cross-domain application scenarios where the primary domain is the same but the subdomain is different.
Implementation principle: both pages are forced to set document.domain as the basic primary domain through js, and the same domain is realized.
Chestnut:
Set document.domain in the parent page http://xxx.com/a.html
Document.domain = 'xxx.com';// is set to the primary domain function test () {alert (document.getElementById (' contacts iframe') .contentWindow); / / contentWindow can get the window object of the child window}
Set up document.domain in the child page http://xxx.com/b.html
Document.domain = 'xxx.com'; / / when iframe loads this page, also set document.domain to make it the same as the document.domain of the main page
Window.postMessage
Window.postMessage is the function of html5, which is the direct data transfer between client and client, which can be transferred either across domains or in the same domain.
The postMessage (data, origin) method accepts two parameters:
The data:html5 specification supports any basic type or replicable object, but some browsers only support strings, so it's best to use JSON.stringify () serialization when passing parameters.
Origin: protocol + host + port number, which can also be set to "*" to indicate that it can be passed to any window, or "/" if you want to specify the same origin as the current window.
Chestnut:
If there is a page, get part of the user information on the page, click to go to another page, the other page is not available by default, you can send part of the user information to this page through window.postMessage. (security and other aspects need to be considered.)
Send a message:
/ / A new window pops up var domain = 'http://haorooms.com'; var myPopup = window.open (`${domain} / windowPostMessageListener.html`,' myWindow'); / / send message setTimeout (function () {var message = {name: "site", sex: "male"}; console.log ('data passed is' + message'); myPopup.postMessage (message, domain);}, 1000)
Receive messages:
/ / listen for message feedback window.addEventListener ('message', function (event) {/ / determine whether the domain name is correct if (event.origin! =' http://haorooms.com') return; console.log ('received response:', event.data);}, false))
As shown in the following figure, accept the page to get the data
If you are using iframe, the code should be written as follows:
/ / capture iframe var domain = 'http://haorooms.com'; var iframe = document.getElementById (' myIFrame'). ContentWindow; / / send message setTimeout (function () {var message = {name: "site", sex: "male"}; console.log ('data passed is:' + message); iframe.postMessage (message, domain);}, 1000)
Receive data and feedback information:
/ / respond to the event window.addEventListener ('message',function (event) {if (event.origin! = =' http://haorooms.com') return; console.log ('message received:' + event.data, event); event.source.postMessage (event.origin);}, false)
Several more important event attributes:
Source-message source, sending window / iframe of the message.
Origin-the URI of the message source (which may contain protocols, domain names, and ports) to validate the data source.
Data-data sent by the sender to the receiver.
Window.name
Principle:
The window object has a name property, which has a characteristic: during the life cycle of a window (window), all pages loaded by a window share a window.name, each page has read and write access to window.name, and window.name persists in all pages loaded by a window.
Chestnut:
Set window.name on the sub-page (b.com/data.html):
/ * b.com/data.html * / window.name ='I was there data; / / here is the data to be transferred. The size is generally 2m, which can be as large as 32m in IE and firefox. / / data formats can be customized, such as json and string
Create an iframe in the parent page (a.com/app.html) and point its src to the child page. Listen to the onload event of iframe on the parent page to obtain the data of the child page:
/ * a.com/app.html * / var iframe = document.createElement ('iframe'); iframe.src =' http://b.com/data.html'; function iframelLoadFn () {var data = iframe.contentWindow.name; console.log (data); / / destroy iframe and free memory after obtaining data; this also ensures security (not to be accessed by other domain frame js). IframeDestoryFn ();} function iframeDestoryFn () {iframe.contentWindow.[ XSS _ clean] (''); iframe.contentWindow.close (); document.body.removeChild (iframe);} if (iframe.attachEvent) {iframe.attachEvent ('onload', iframelLoadFn);} else {iframe.onload = iframelLoadFn;} document.body.appendChild (iframe)
Http-proxy-middleware
Http-proxy-middleware is the middleware used to forward request agents to other servers.
Installation:
Npm install http-proxy-middleware-save-dev
The configuration is as follows:
Module.exports = {devServer: {contentBase: path.resolve (_ _ dirname, 'dev'), publicPath:' /', historyApiFallback: true, proxy: {/ / requests to'/ device' are proxied to target: http://target.com'/ device/*': {target: 'http://target.com', secure: false / / accept the service changeOrigin: true} running on https
The use is as follows:
Fetch ('/ device/space') .then (res = > {/ / proxied to http://target.com/device/space return res.json ();}); / / the url used must start with / otherwise it will not be proxied to the specified address fetch ('device/space') .then (res = > {/ / http://localhost:8080/device/space access local service return res.json ();})
Nginx reverse proxy
Reverse proxy (Reverse Proxy) means that the proxy server accepts the connection request from the client, then forwards the request to the server on the internal network, and returns the results obtained from the server to the client. At this time, the proxy server behaves as a server.
The reverse proxy server is like the original server to the client, and the client does not need to make any special settings. The client sends a normal request to the content in the reverse proxy's namespace (name-space), which then determines where to forward the request (the original server) and returns the obtained content to the client as if it were already its own.
Modularization
AMD/CMD/CommonJs is the standard of JS modular development. At present, the corresponding implementations are RequireJS,SeaJs, nodeJs.
CommonJS: server js
CommonJS is a set of specification that aims to build a javaScript ecosystem outside the browser environment. It is mainly defined as a module form to solve the scope problem of javaScript, and each module can be executed in its own namespace.
Implementation method: the module must export external variables or interfaces through module.exports, and import the output of other modules into the scope of the current module through require ().
Mainly for the server side (synchronous loading files) and desktop environment, node.js follows the specification of CommonJS; the CommonJS loading module is synchronous, so the later operation can be performed only when the loading is completed.
Require () is used to introduce external modules
The exports object is used to export the method or variable of the current module, the only exit
The module object represents the module itself.
/ / define a module.js file var A = () = > console.log ('I am the defined module'); / / 1. The first return method is module.exports = A; / / 2. The second return method module.exports.test = A / / 3. The third return method exports.test = A; / / define a test.js file [the two files are in the same directory] var module = require (". / module"); / / call this module, different return methods call / / 1. The first method is module (); / / 2. The second method is module.test (); / / 3. The third way to call module.test (); / / execute the file node test.js
AMD: asynchronous module definition [browser-side js]
AMD is the abbreviation of Asynchronous Module Definition, which means asynchronous module definition; the module is loaded asynchronously, which does not affect the operation of the following statements when loading the module. It is mainly a set of specifications for the performance of the front-end js.
Realization method: define the module through the define method, and load the module through the require method.
Define (id?,dependencies?,factory): it makes all the dependencies when declaring the module (dep) and passes it to factory as a formal reference. There is no dependence, just define a simple module (or independent module)
Require ([modules], callback): the first parameter [modules] is the array of module names to be loaded, and the second parameter callback is the callback function after the module is loaded successfully.
Mainly aimed at browser js,requireJs, it follows the specification of AMD.
/ / module1.js file that defines independent modules define ({methodA: () = > console.log ('I am methodA' of module1); methodB: () = > console.log ('I am methodB' of module1);}); / / module2.js file, another way to define stand-alone modules define () = > {return {module: () = > console.log ('I am methodA' of module2) MethodB: () = > console.log ('I am methodB' of module2);};}); / / module3.js file that defines a non-independent module (this module depends on other modules) define (['module1',' module2'], (M1, m2) = > {return {methodC: () = > {m1.methodA (); m2.methodB ()) }};}); / / define a main.js to load these modules require (['module3'], (m3) = > {m3.methodC ();}) / / in order to avoid causing the page to become unresponsive, there are two solutions, one is to load it at the bottom of the page, and the other is to write it as follows: / / the async attribute indicates that the file needs to be loaded asynchronously to prevent the page from losing response. / / IE does not support this attribute, only defer is supported, so write defer as well. / / data-main attribute: specify the main module of the web program / / console output result I am methodA of module1 and I am methodB of module2
CMD: general module definition [browser-side js]
CMD is the abbreviation of Common Module Definition, which loads the module asynchronously. When loading, the module will be parsed into a string to know which module it depends on.
Mainly for the browser side (asynchronously loading files), loading files on demand. The corresponding implementation is seajs
The difference between AMD and CMD
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
For dependent modules, AMD is executed in advance and CMD is deferred. However, RequireJS has been changed to delay execution since 2. 0 (different processing methods depending on how you write it). CMD favors as lazy as possible (lazy loading as much as possible, also known as lazy loading, that is, loading only when needed).
CMD favors relying on proximity, while AMD favors relying on front.
/ / CMD define (function (require, exports, module) {var a = require ('. / a'); a.doSomething (); / /. Var b = require ('. / b'); / / dependency can be written nearby b.doSomething (); / /.}) / / AMD define (['. / averse,'. / b'], function (a, b) {/ / dependency must write a.doSomething () at the beginning; / /. B.doSomething (); / /...})
The difference between import and require
Both import and require are modular.
Require is the syntax of CommonJs (how the AMD specification is introduced), and the module of CommonJs is the object. Import is a syntax standard of es6 (browsers do not support it, essentially using babel in node to transcode es6 to es5 and then execute, import will be transcoded to require), es6 module is not an object.
Require is a method that loads the entire module (that is, all the methods in the module) at run time, generates an object, and then reads it from the object (this object can only be obtained at run time, not static at compile time), and can theoretically be used anywhere in the code. Import is called at compile time to determine the dependency of the module, input variables (the es6 module is not an object, but the output code is specified through the export command, and then input through import, only the methods derived in import are loaded, other methods are not loaded), import has an enhanced effect and will be promoted to the head of the module (executed at compile time)
Export and import can be anywhere in the module, but they must be at the top of the module, and errors will be reported if they are in other scopes (designs like es6 can improve compiler efficiency, but not runtime loading).
Require is an assignment process that assigns the result of require (objects, numbers, functions, etc.) to a variable (copy or shallow copy), by default an object of export. Import is the deconstruction process (who needs it and who loads it).
Require/exports:
/ / require: what is really coming out by require is the content of the memory block pointed to by module.exports const a = require ('a') / exports: just a reference to module.exports, which assists module.exports to operate the data in memory exports.a = a module.exports = a
Import/export:
/ / import import a from'asides; import {default as a} from'asides; import * as a from'asides; import {fun1,fun2} from'acodes; / / export export default a; export const a = 1; export functon a {...}; export {fun1,fun2}
Http and https
Http: hypertext transfer Protocol (Http,HyperText Transfer Protocol) is the most widely used network protocol on the Internet. Http was originally designed to provide a way to publish and receive HTML pages. It can make browsers more efficient.
Http protocol sends messages in clear text, and if hackers intercept the transmission messages between Web browsers and servers, they can get the information directly.
Https: a security-oriented Http channel, a secure version of Http. The security foundation of Https is SSL. SSL protocol is located between TCP/IP protocol and various application layer protocols, which provides security support for data communication. SSL protocol can be divided into two layers: SSL recording Protocol (SSL Record Protocol), which is based on reliable transport protocols such as TCP, and provides support for high-level protocols such as data encapsulation, compression, encryption and other basic functions.
SSL handshake protocol (SSL Handshake Protocol), which is based on SSL recording protocol, is used for identity authentication, negotiation of encryption algorithm, exchange of encryption keys and so on before the actual data transmission begins.
The difference between HTTP and HTTPS
1. HTTP is a hypertext transmission protocol, information is plaintext transmission, and HTTPS is a secure SSL encrypted transmission protocol.
2. HTTPS protocol requires ca to apply for a certificate. Generally, there are few free certificates, so it costs a certain fee.
3. HTTP and HTTPS use completely different connection methods and different ports. The former is 80 and the latter is 443.
4. HTTP connection is stateless. HTTPS protocol is a network protocol constructed by SSL+HTTP protocol for encrypted transmission and identity authentication, and its security is higher than that of HTTP protocol.
Advantages of https
Although HTTPS is not absolutely secure, and organizations with root certificates and encryption algorithms can also carry out man-in-the-middle attacks, HTTPS is still the most secure solution under the current architecture, with the following main benefits:
1) use HTTPS protocol to authenticate users and servers to ensure that data is sent to the correct clients and servers
2) HTTPS protocol is a network protocol constructed by SSL+HTTP protocol for encrypted transmission and identity authentication, which is more secure than http protocol. It can prevent data from being stolen and changed in the process of transmission, and ensure the integrity of data.
3) HTTPS is the most secure solution under the current architecture, although it is not absolutely secure, it greatly increases the cost of man-in-the-middle attacks.
4) Google adjusted its search engine algorithm in August 2014, saying that "sites encrypted with HTTPS will rank higher in search results than their equivalent HTTP sites."
Shortcomings of Https
1) the handshake phase of Https protocol is time-consuming, which will prolong the loading time of the page.
2) Https connection cache is not as efficient as Http, which will increase data overhead, and even existing security measures will be affected.
3) SSL certificates usually need to be bound to IP. You cannot bind multiple domain names to the same IP. IPv4 resources cannot support this consumption.
4) the encryption range of Https protocol is also limited. Most importantly, the credit chain system of SSL certificate is not secure, especially when some countries can control CA root certificate, man-in-the-middle attack is also feasible.
Ergodic method
For
In the for loop, the loop gets the values of an array or an array of similar objects, such as arguments and HTMLCollection objects.
Deficiency:
Is that each loop requires the length of the array to be obtained.
The termination conditions should be clear.
Foreach (), map ()
Both methods can traverse each element of the array, and the parameters are the same
ForEach (): executes the provided function on each element of the array once, always returning undefined
Map (): creates a new array that results in the result that each element in the array calls a provided function. The return value is a new array
Var array1 = [1Jing 2 Jing 3 Jing 4 Jing 5]; var x = array1.forEach ((value,index) = > {console.log (value); return value + 10;}); console.log (x); / / undefined var y = array1.map ((value,index) = > {console.log (value); return value + 10;}); console.log (y); / / [11, 12, 13, 14, 15]
For in
It is often used to iterate over each element of an object's attribute or array, which contains the name of the current attribute or the index of the current array element.
When traversing an object, the variable I is the loop counter as the property name of the object, traversing the enumerable properties of an object in any order. For each different attribute, the statement is executed.
When traversing an array, the variable I is the index of the current array element by the loop counter.
Deficiency:
The for..in loop traverses the methods and properties in a type of prototype.
Const array = ["admin", "manager", "db"]; array.color = 'red'; array.prototype.name= "zhangshan"; for (var i in array) {if (array.hasOwnProperty (I)) {console.log (array [I]); / / admin,manager,db,color}} / / hasOwnProperty (): the property or method of the object is non-inherited and returns true
For... Of
Iteration loops iterate over objects (including Array,Map,Set,String,TypedArray,arguments objects), and so on. Objects cannot be traversed. Loop only the elements of the collection itself
Var a = ['A','B','C']; var s = new Set (['A','B','C']); var m = new Map ([[1,'x'], [2,'y'], [3,'z']); a.name = 'array'; for (var x of a) {console.log (x) / / 'Aids,' breads,'C'} for (var x of s) {console.log (x); / / 'Aids,' breads,'C'} for (var x of m) {console.log (x [0] +'='+ x [1]); / / 1doesn't have a history.
Inherit
/ / define an animal class function Animal (name) {/ / attribute this.name = name | | 'Animal'; / / instance method this.sleep = function () {console.log (this.name +' sleeping!') ;} / / prototype method Animal.prototype.eat = function (food) {console.log (this.name + 'eating:' + food);}
Prototype chain inheritance
Core: use the instance of the parent class as the prototype of the subclass.
Function Dog (age) {this.age = age;} Dog.protoType = New Animal (); Dog.prototype.name = 'dog'; const dog = new Dog (12); console.log (dog.name); console.log (dog.eat (' age')); console.log (dog instanceof Animal); / / true console.log (dog instanceof Dog); / / true
New takes the following steps to create a new instance object:
1. Create a new object
two。 Point the _ proto_ of the new object to the prototype object of the constructor
3. Assign the scope of the constructor to the new object (that is, this points to the new object)
4. Execute the code in the constructor (add properties for this new object)
5. Return to the new object
/ / 1. Create a new object var Obj = {}; / / 2. Point the _ proto_ of the new object to the prototype object of the constructor Obj._proto_ = Animal.prototype (); / / 3. Execute the code in the constructor (add properties to this new object) Animal.call (Obj); / / 4. Returns the new object return Obj
Features:
1. The properties that can be inherited by an instance are: the constructor property of the instance, the constructor property of the parent class, and the property of the parent prototype.
two。 A very pure inheritance relationship. An instance is an instance of a subclass and an instance of a parent class.
3. The parent class adds prototype methods / prototype properties, which can be accessed by all subclasses.
Disadvantages:
1. The new instance cannot pass parameters to the parent class constructor.
two。 Inherit a single.
3. All new instances share the properties of the parent instance. (the properties on the prototype are shared, one instance modifies the prototype properties, and the other instance's prototype properties are modified!)
4. To add properties and methods on a prototype to a subclass, it must be executed after a statement such as new Animal () and cannot be placed in the constructor
Constructor inheritance
Core: using the constructor of the parent class to enhance the subclass instance is tantamount to copying the instance properties of the parent class to the subclass (no prototype is used)
Function Dog (name) {Animal.apply (this, 'dog'); this.name = name;} const dog = new Dog (); console.log (dog.name); console.log (dog.eat (' age')); console.log (dog instanceof Animal); / / false console.log (dog instanceof Dog); / / true
Important: introduce the parent constructor into the subclass function with .call () and .apply () (self-execute (copy) the parent function in the subclass function)
Features:
1. Inherits only the properties of the parent class constructor, not the parent prototype.
two。 The shortcomings of prototype chain inheritance 1, 2, 3 are solved.
3. You can implement multiple inheritance, inheriting multiple constructor attributes (multiple call).
4. Parameters can be passed to the parent instance in the child instance.
Disadvantages:
1. Can inherit the properties of the parent class constructor.
two。 Unable to reuse the constructor. (reinvokes every time you use it)
3. Each new instance has a bloated copy of the parent constructor.
4. An instance is not an instance of a parent class, but an instance of a subclass
Composite inheritance (prototype chain inheritance and constructor inheritance) (commonly used)
Core: inherit the properties of the parent class and retain the advantages of passing parameters by calling the parent class construction, and then realize function reuse by using the parent class instance as the subclass prototype
Function Cat (name) {Animal.call (this, name); this.name = name;} Cat.prototype = new Animal (); Cat.prototype.constructor = Cat; var cat = new Cat (); console.log (cat.name); console.log (cat.sleep ()); console.log (cat instanceof Animal); / / true console.log (cat instanceof Cat); / / true
Key points: combine the advantages of the two modes, parameter transfer and reuse
Features:
1. Can inherit the properties on the parent class prototype, pass parameters, and can be reused.
two。 The constructor properties introduced by each new instance are private.
3. Is an instance of both a subclass and a parent class
Disadvantages:
The parent constructor is called twice (memory consumption), and the constructor of the subclass replaces the parent constructor on the prototype.
Prototype inheritance
Important: wrap an object with a function, and then return the call to the function, and the function becomes an instance or object that can add properties at will. This is how object.create () works.
Features:
It is similar to copying an object and wrapping it with functions.
Disadvantages:
1. All instances inherit the properties on the prototype.
two。 Unable to implement reuse. (new instance properties are added later)
Parasitic inheritance
The key point is to put a shell on the outside of the prototype inheritance.
Advantage: no custom type is created, because it is just a shell return object (this), and this function naturally becomes the new object created.
Disadvantages: no prototypes are used and cannot be reused.
Parasitic combinatorial inheritance (commonly used)
Parasitism: returns an object within a function and then calls the
Combination:
1. The prototype of the function is equal to another instance.
2. Use apply or call to introduce another constructor in the function, which can pass parameters.
Function Cat (name) {Animal.call (this); this.name = name | | 'Tom';} (function () {/ / create a class with no instance method var Super = function () {}; Super.prototype = Animal.prototype; / / prototype Cat.prototype = new Super ();}) () (); var cat = new Cat (); Cat.prototype.constructor = Cat / / the constructor console.log (cat.name); console.log (cat.sleep ()); console.log (cat instanceof Animal); / / true console.log (cat instanceof Cat); / / true needs to be repaired. At this point, the study on "sorting out and summarizing the basic knowledge of the front end" is over. I hope it can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.