Summary of front-end knowledge points - JS advanced (under continuous update)

JavaScript language 2020-11-13 05:04:17
summary front-end end knowledge points

Summary of front-end knowledge points ——JS senior ( Ongoing update )

1. character string

What is? : An array of characters that continuously stores multiple characters
identical : 1. Subscript 2. .length 3. Traverse

4\. selection : slice(starti[, endi])

Different : Different types API Not universal
API: All strings API No right to modify the original string , Always return new strings

  1. toggle case :
    Unified capitalization : str=str.toUpperCase()
    Unified to lowercase : str=str.toLowerCase()
    when : Case insensitive , All need to be converted to consistent case first , Compare again .

explain : Captcha should not be done by the client , It should be done by the server side

2. Gets the character at the specified position :

str.charAt(i) => str[i]
Gets the character of the specified position unicode Number

 take unicode Change the sign to Chinese character : String.fromCharCode(unicode)

3. Get substring :

emphasize : If one API, Both parameters are subscripts , Then the latter parameter +1( With head and no tail )
str.substring(starti,endi+1) Usage and slice Exactly the same as
emphasize : Negative parameter... Is not supported
str.subStr(starti,n) from starti Start , take n individual
emphasize : The second parameter is not a subscript , therefore , You don't have to think about the head, not the tail

4. lookup : 4 Kind of :

  1. Find the location of a fixed keyword :
    var i=str.indexOf(“ key word ”[,fromi])
    stay str in ,fromi After the position , Find the next one " key word " Position of appearance
    If you find , Returns the subscript position of the first word of a keyword
    If not , return -1
    explain : fromi Omission , The default from the 0 Start

    var i=str.lastIndexOf(“ key word ”);
    stay str in , lookup " key word " The last place

    problem : Can only find a fixed keyword
    Lie on my grass / fuck / acutely / Slot
    tiny Letter w x wei xin
    solve : Using regular search :

  2. Determine whether keywords are included :
    var Regular /)
    Return value : If you find , Return the position of the keyword

     If not , return -1

    problem : Default , All regularities are case sensitive
    solve : In the second / After add i ignore Ignore
    problem : You can only get positions , Unable to obtain the content of sensitive words found this time

  3. Get the content of the keyword :
    var arr=str.match(/ Regular /i);
    2 In this case :

    1. No addition g The situation of : Can only return the first found keyword content and location : [ 0: “ Key words content ”, index: Location ]
    2. Add g: Returns the content of all sensitive words found , Save in array .g: global

emphasize : If you can't find it , return null

 Warning : Any function may return null! We must judge that it is not null, Ability to use !

problem : Only get keyword content , Can't get location

  1. That is to find the content of each keyword , Find each keyword location again :

5. Replace :

What is? : Replace the keyword found with the specified content
how : 2 Kind of :

  1. Simple replacement : Replace all sensitive words with the same new value
    str=str.replace(/ Regular /,“ Replacement value ”)

  2. Advanced replacement : According to the difference of each sensitive word , Replace different values separately
    str=str.replace(/ Regular /,function(kw){

     //kw: Will automatically get a keyword found this time
    return according to kw Different , Dynamically generate different replacement values


derivative : Delete keywords :
str=str.replace(/ Regular /,"")

6. Regular expressions : Regular Expression

What is? : An expression that describes the rules for the occurrence of characters in a string
when : 2 Kind of :

  1. Search for keywords :
  2. verification :

how : regular expression syntax :

  1. The simplest regularization is actually the keyword text :

7. Character set :

What is? : Specify one character , A collection of alternative character lists
when : Just one character , When there are many alternative words
how : [ List of alternative characters ]
emphasize : One [] Only one character can be matched
Abbreviation : If some of the characters in the list of alternative characters are continuous

 It can be abbreviated as : [x-x] use - Omit the middle character
such as : [0-9] One digit
[a-z] A lowercase character
[A-Z] A capital letter
[A-Za-z] One character
[0-9A-Za-z] A letter or number
[\u4e00-\u9fa5] A Chinese character

Reverse election : 1 except 4 and 7 Will do

8. Predefined character set : 4 Kind of :

d One digit [0-9]
w One digit , Letters or underscores [0-9A-Za-z_]
emphasize : Only 100% When the match , Only use w, If it is not allowed to have _, The custom character set is used
s A null character , such as : Space ,Tab,…
. wildcard
problem : A character set can only specify the content of a character , The number of characters cannot be flexibly specified

9. quantifiers :

What is? : A rule that specifies the number of occurrences of a character set
when : As long as you specify the number of times the character set appears , All quantifiers
how : Character set quantifiers
emphasize : By default, the quantifier only modifies the adjacent previous character set
Include : 2 Categories: :

1\. There is a clear quantity boundary :
{6,8} least 6 Time , most 8 Time
{6,} least 6 Time , There is no limit
{6} must 6 Time , No more, no less
2\. There is no clear quantitative boundary :
? not essential , most 1 Time
* not essential , There is no limit
+ At least 1 Time , There is no limit

10. Selection and grouping :

  1. choice : or
    The rules 1| The rules 2
    when : Just choose one of the two rules to match

  2. grouping : ( The rules 1 The rules 2…)
    when : If you want a quantifier to modify multiple rules at the same time , You have to divide multiple rules into a group , Use quantifiers to modify groups .

     such as : license plate number : [\u4e00-\u9fa5][A-Z]•[0-9A-Z]{5}
    such as : Mobile phone number rules :
    \+86 or 0086 not essential , most 1 Time
    Null character not essential , There is no limit
    stay 3,4,5,7,8 Appoint one

    9 Digit number

     such as : ID number :

    15 Digit number 2 Digit number A digit or X

     not essential , At most once
    such as : E-mail : despise

    /^([a-zA-Z0-9_-])[email protected]([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    such as : url:

11. Match special locations : 3 individual :

  1. Start of string : ^

  2. End of string : $
    such as : The empty character at the beginning : ^s+

     The end of a null character : \s+$
    An empty character at the beginning or end : ^\s+|\s+$

    3. Word boundaries : b The beginning includes , ending , Null character , Punctuation

     such as : Word initials : \b[a-z]
    Match words : \bxxx\b


Replace : 2 Kind of : If the keyword is fixed :
str=str.replace(“ key word ”,“ Replacement value ”);
If the keyword changes
str=str.replace(/ Regular /ig,“ Replacement value ”);
cutting : 2 Kind of : If the separator is fixed :
var substrs=str.split(“ Separator ”)
If the separator is not fixed
var substrs=str.split(/ Regular /i)
Fixed routine : Break a string into an array of characters

 var chars=str.split("")


What is? : Save a regular expression , And provides regular expressions for validation and lookup API
when : Just use regular search keywords or verify string format
how :
establish : 2 Kind of :

  1. Direct measurement : var reg=/ Regular /ig
    when : As long as the rules of regular expressions are fixed .
    problem : Regular expressions are fixed , Dynamic generation is not supported
  2. new: var reg=new RegExp(“ Regular ”,“ig”);
    when : As long as you need to dynamically generate regular expressions

API: 2 individual :

  1. verification : var bool=reg.test(str)
    problem : Default , Just find the match , Just go back to true, No complete matching is required !
    solve : In the future , All verification must be preceded by ^, After add $
  2. lookup : That is to find each keyword position , And get every keyword content
    var arr=reg.exec(str)
    stay str Find the location and content of the next keyword in
    Return value : arr:[ 0: Content , index: Location ]
    If you can't find it , return null
    If you look for all : Just use while Call again and again reg.exec that will do ,exec Can automatically jump to the next search location


What is? : Save the constants of the mathematical calculation and API The object of
when : Do arithmetic
how :
establish : No need to create , all API Use both Math Call directly

    1. integer :
      Round up : Math.ceil(num)
      Round down :
      parseInt(str) Remove non numeric characters at the end of a string ( Company )
      Round to the nearest whole :
      optimal : Returns the number type , It can be calculated directly
      Lack of : You can't specify the number of decimal places at will
      optimal : You can specify the decimal places at will
      Lack of : Return string type , You can't add directly
      Customize round
  1. Power and square root :
    Math.pow( base number , power )

  2. Maximum and minimum
    Math.max( value 1, value 2,…)
    Math.min( value 1, value 2,…)
    problem : Arrays are not supported
    solve : Math.max(…arr)

  3. random number :
    Math.random() 0~1 Random decimal
    The formula : stay min To max Take a random integer between
    Abbreviation : stay 0~max Take a random integer between

  4. Trigonometric functions :
    Given the angle , Seeking side length , Using trigonometric functions : sin cos tan
    Known side length , Find the angle , With the inverse trigonometric function : asin acos atan
    Only with atan:
    var radian =Math.atan( To the side chief / Next to me )

    360 angle =2π radian

    problem : atan Can't distinguish the quadrant of the angle
    solve : Math.atan2( To the side chief , Next to me );


What is? : Save for a time , Provide the operation time API
when : Just store time or operation time in the program , Use both date
how :
establish : 4 Kind of :

  1. Create date object , And automatically get the current system time of the client
    var now=new Date();
  2. Create date object , Save custom time
    var now=new Date(“yyyy/MM/dd hh:mm:ss”);
  3. Create a date object in milliseconds :
    var date=new Date(ms)
  4. Copy a date object :
    problem : The calculation of date is to modify the original date object directly
    solve : If you want to keep both the start and end times before and after the calculation , Copy the start time first , Use the copy to calculate the end time
    var date2=new Date(date1)

The essence : The starting date of a huge object is saved in milliseconds :

1970 year 1 month 1 Millisecond of day to date

Question of date of text storage :

1\. Sometimes the problem is :
2\. It's not easy to calculate :

Milliseconds store date :

1\. Free from time zone interference :
2\. Easy to calculate :

summary : In the future, time will be transmitted over the network or stored in a database , In milliseconds


  1. 8 A unit of :
    FullYear Month Date Day
    Hours Minutes Seconds Milliseconds
  2. There's a couple on each unit get/set Method :
    getXXX() Responsible for getting the value of the unit
    setXXX() Responsible for modifying the unit value
    special case : Day Do not modify , No, setDay()
  3. Value range :
    Month: 0~11 The month in the computer is always smaller than the reality 1
    Date: 1~31
    Day: 0~6
    Hours: 0~23
    Minutes/Seconds: 0~59

Date calculation :

  1. The two dates are subtractive : What we get is a millisecond difference
    when : Calculate the time period or count the countdown

  2. Add or subtract from any unit : 3 Step :

    1. Get the current value of the unit
    2. Add and subtract
    3. The results will be calculated set Go back
      setXXX() Can adjust the time base automatically

Can be simplified as : date.setXXX(date.getXXX()+n)
problem : setXXX() Modify the original date directly
solve : If you save both the start and end times before and after the calculation , You should copy the copy first , And then calculate with copies .


Date formatting :
date.toString() Default local time full format
date.toLocaleString() To a simplified version of local time
date.toLocaleDateString() Keep only the date part
date.toLocaleTimeString() Keep only the time part


What is a mistake : Program execution , Exception encountered that cannot continue execution
Program error , Will be forced to break out of .
What is error handling : Even if the program goes wrong ! And it's guaranteed that you won't stop quitting
when : If you want the program , Even if something goes wrong , And it won't force you to quit
how :
Normal code that could have been wrong
//err: Error object , Automatically save the wrong information
Error handling code that is executed only when there is an error :
Error message , Log , Release resources
problem : It's a little inefficient
solve : Most of the try catch, Can be used if…else Instead of

Actively throw errors :
throw new Error(“ error message ”)
despise : js There are several types of errors in the Communist Party of China : 6 Kind of :
SyntaxError Grammar mistakes
ReferenceError Misquote
TypeError Type error
RangeError Range error Parameter out of range

EvalError URIError


What is a function : Object that holds a piece of code , Give me another name .
Why? : code reuse
when : As long as a piece of code is likely to be reused !
how :
establish : 3 Kind of :

  1. Statement : function Function name ( parameter list ){

     The body of the function ;
    return Return value ;

    Parameters : When you call a function , A variable that receives data from an incoming function
    when : If the function itself must have some data to execute properly , You have to define parameters , Receiving the necessary data from the outside
    Return value : Function execution result
    when : If the caller needs to get the execution result of the function
    call : var Return value = Function name ( Parameter value list );
    problem : A statement in advance : Before the program starts to execute , First the var Declared variables and function Declared function , Advance to the top of the current scope to create . The assignment remains in place .
    solve :

  2. Direct measurement : var Function name =function ( parameter list ){
    characteristic : Will not be declared ahead of time
    reveal : It's just a function name

     A function is actually an object that holds a snippet of code
    Function name refers to function object through object address
  3. new :
    var Function name =
    new Function(“ Parameters 1”,“ Parameters 2”,…,“ The body of the function ”)

20. heavy load overload:

What is? : Multiple identical function names , Functions with different parameter lists , In the call , Depending on the parameters passed in , Perform different operations automatically .
Why? : In order to reduce the API The number of , Lighten the burden on the caller
when : Just one task , Depending on the parameters passed in , When performing different processes .
how : js Syntax default does not support overloading !

 because : js Multiple functions with the same name are not allowed in , At the same time . The last function will override the previous one .
Flexible implementation : arguments
What is? : In each function , Automatically included , Class array object that receives the parameter values of all incoming functions
Class array object : Objects that look like arrays
vs Array : identical : 1. Subscript , 2. .length, 3. Traverse
Different : Different types , API Not universal
web Front end development live tutorial Q-q-u-n: 767273102 , There are free development tools for rice , Zero basis , Advanced video tutorial , I hope novices don't take detours

21. Anonymous functions :

What is? : When defining a function , Function name is not specified
Why? : To save memory or Divide the temporary scope
when :

  1. Just one function , Hope to call , It's automatically released immediately !
  2. Divide the temporary scope :

how :

  1. Callback : After defining the function , Don't call yourself , It's passed to another function to call
  2. Self tuning : After defining the function , Call yourself now .
    when : In the future all of js The code has to be in anonymous function self tuning , Avoid global pollution .

22. Garbage collection :

What is rubbish : An object that is no longer used by any variable
What is garbage collection : js The engine will automatically reclaim space for objects that are no longer in use .
Why? : Memory space is limited !
Garbage collector : A small program dedicated to recycling garbage objects ——js The engine comes with
how :

  1. When the program is executed , The garbage collector is executed with the execution of the main program .
  2. Every time an object is created , The garbage collector will record that the object is referenced by several variables .
  3. If it is found that an object is no longer applied by any variable , Automatically reclaims the storage space of the object .

Good habits : As long as an object is no longer used , You have to assign it to null

23. Scope and scope chain

Scope (scope): The available range of a variable
Why? : Avoid the influence of internal variables on the external
The essence : Is an object that stores variables
Include : 2 Kind of :

  1. Global scope : window
    Save global variables : used anywhere , Can be used repeatedly
  2. Function scope : ?
    Save local variable : Available only within functions , And it's not reusable !

24. Function life cycle :

  1. Before the program starts to execute
    Create an execution environment stack in memory ( Array ): Used to save the calling function task .
    Add the first record to the execution environment station : Call the browser main program
    Create a global scope object window: 2 A role :

    1\. Save the data and objects the browser needs
    2\. As a global scope object for a program , Save global variables
  2. When defining a function :
    stay window Define function name variable in
    Create a function object to save the function definition
    Function name variable references function object
    Function object's scope attribute , It also points back to the scope of the function when it was created

  3. When you call a function
    Add the record of this function call in the execution environment stack
    Create the function scope object of this function call AO
    stay AO Add the local variable of the function in
    Set up AO Of parent Pointing to a function scope
    Function call records in the execution environment stack , quote AO
    The order in which variables are used : First use the local , And then the whole picture

  4. After function call
    The record of this function call is put out of the stack of the execution environment
    Lead to AO Be released , Causes all local variables to be released

25. Scope chain :

What is? : By multi-level scope objects , A chain structure formed by successive references
2 A role :

  1. Save all variables
  2. Controls the order in which variables are used !

26. Closure closure:

What is? : That is to reuse a variable , And a mechanism to protect variables from pollution
Why? : Global variables and local variables have their own advantages and disadvantages :
Global variables : optimal : reusable , Lack of : Susceptible to pollution
local variable : optimal : Only available within functions , Will not be polluted

 Lack of : Not reusable !

when : Just one variable , May be reused , And don't want to be tampered with
how : 3 Step :

  1. Wrap variables to be protected and inner functions with outer functions
  2. Outer function returns inner function to outer
  3. Call outer function , The object that gets the inner function , Stored in external variables —— It forms a closure

Why closures are formed : After the outer function is called , The function scope object of the outer function cannot be released
Active use of closures : Bind a specific variable to a function
despise : Draw a sketch

  1. Find protected variables , And determine the final value

  2. Look for inner function objects
    The outer function returns the inner function object outward : 3 Kind of :

    1. return function(){}
    2. Global variables =function(){}
    3. return arr/obj{function(){…}}


What is an object : The independent storage space in memory that stores multiple data is called an object .
What is object-oriented : In the program, object structure is used to describe a specific thing in reality .
Why? : In order to facilitate the maintenance and search of large amounts of data
when : Almost all js Program , They are developed in an object-oriented way
how : Three characteristics : encapsulation , Inherit , polymorphic
encapsulation : Object is used to describe the attributes and functions of a specific thing in reality
Why? : Easy to maintain and find
when : In the future, just use the object-oriented method to develop , You should encapsulate the object first , Properties and functionality of objects on demand .
how : 3 Kind of :

  1. use {}:
    var obj={
    Property name : value ,

    ... : ... ,

    // Method name :function(){…},
    Method name (){…},
    among : The attribute value of an object becomes the property of an object

     The property of an object is essentially a variable stored in an object
    The function of things becomes the method of object !
    The essence of a method is a function stored in an object

    How to access members of objects :
    Properties of the access object : object . Property name
    Method of calling object : object . Method name ()
    problem : The object's own properties should be used in its own methods
    error : Use the attribute name directly , Report errors : Variable not found

     Why? : Default , No addition . Just use the variable , Can only be found in the scope chain , Cannot automatically enter object

    Solve one : Object name . Property name

     problem : The object name is just a normal variable name , It could change .

    Correct the problem : this. Property name
    this: Automatically refers to the... That is calling the current method . The former object

     Why? : Not affected by object name variables
    when : When you access your own object, you only need to access its own properties , You have to add this.

js The nature of the object in , It's actually an associative array

  1. use new:
    var obj=new Object(); // Create an empty object Equivalent to {}
    obj. Property name = value ;
    obj. Method name =function(){
    … this. Property name …

Just like an associative array ,js You can also add new properties and methods at any time .
problem : When multiple objects of the same structure are created repeatedly , Too much duplicate code , It makes it difficult to maintain
solve :

  1. Use constructors :
    Constructors : A function that describes the unified structure of a class of objects
    Why? : To reuse structural code !
    when : As long as you repeatedly create multiple objects of the same structure , They all use constructors
    how : 2 Step :

    1. Define the constructor
      function Type name ( Attribute parameter list ){
      this. Property name = Property parameters ;
      this. … = Property parameters ;
      this. Method name =function(){


    2. Call the constructor to create a new object
      var obj=new Type name ( List of attribute values )
      new: 1. Create a new empty object

       2. Set the new object to inherit the prototype object of the constructor
      3. Call the constructor with the new object
      In the constructor this All point to new objects
      4. Returns the address of the new object

problem : Constructors can only reuse code , Can't save memory !
solve : Inherit :

28. Inherit :

What is? : Members of the parent object , Sub objects do not need to be created , It can be used directly
Why? : code reuse , To save memory
when : Just multiple child objects , When you have the same members , You should define only one in the parent object , All sub objects are shared !
how : js All the objects in the prototype are implemented through

 What is a prototype object : Centralized storage of all sub objects of the same type , The parent object of a shared member
when : As long as inherit , The necessary archetype object
how :
establish : No need to create , Buy one for free
Every constructor created , All of them have a prototype object
Inherit : When creating sub objects ,new Of the 2 Step automatically sets the child object to inherit the prototype object of the constructor
Visiting members : Priority access to own members
I don't have , Just go to the father ( Prototype object ) Search for
Add members to the prototype object :
Constructors .prototype. member = value

Own and shared properties :
own property : Save in the current object local , Only properties unique to the current object
Common property : Save in the parent object , Properties common to all child objects
Read property values : Sub object . attribute
Modify attribute values : own property , It must be modified by the child object itself

 Common property , You can only modify with prototype objects !

Prototype objects for built-in objects :
despise : Built-in objects : 11 individual :

String Number Boolean —— Package type object
Array Date RegExp Math
Function Object
Global ( In the browser , By window Instead of )

despise : Understanding of packaging types

 What is? : Save a value of the original type , And provide the operation of the original type value API
Why? : The value of the primitive type itself has no function
when : Just try to call... On the value of the original type API when , The wrapper type object is automatically used to help the values of the original type to perform operations .
how :
1. There are three types of wrapping objects in memory :
String Number Boolean
2. Trying to call the value of the original type API when , Automatically detect the type name of the value of the original type
var n=345.678;
typeof n => number
3. Instantiate the corresponding wrapper type object according to the type name , Call its API
new Number(n).toFixed(2) => 345.68
4. After execution , Wrapper type objects are released automatically
new Number Release !


Three characteristics of object oriented : encapsulation , Inherit , polymorphic
Inherit :
Prototype object :
Prototype objects of built-in types :
One type : It has two parts :

1\. Constructors : Create a child object of this type
2\. Prototype object : Save the common members of all child objects

Solve browser compatibility issues : Old browsers can't use new API

1\. Determine whether the prototype object of the corresponding type in the current browser contains the API
2\. If not , Then customize the API, Add to the prototype object of the corresponding type

30. Prototype chain :

What is? : By multi-level parent object , Chain structure formed by successive inheritance
preserved : Properties of all objects
Controls the : The order in which object properties are used :

 First of all , And then there is

despise : How to judge whether an object is an array type ? There are several ways
error : typeof : Only primitive types can be distinguished , function , The specific type name of a reference type object cannot be further distinguished
correct : 4 Kind of :

  1. Judging prototype objects :
  2. Judge the constructor :
    obj instanceof Array

problem : Not strictly , Not only check the direct parent object , And check the entire prototype chain

  1. Judge the internal of the object class attribute

class attribute : An attribute inside an object that specifically records the type name of the object when it is created
problem 1: class Property is an internal property , No use . Direct access
solve : The only way : Object.prototype.toString()
problem 2: Each type of prototype object rewrites its own toString() Method , Child object cannot be called to Object.prototype.toString()
solve : Give Way obj Force any one of fun
In the moment of execution : obj.toString()
result :"[object Class]"

despise : When to define a method in a prototype object , When to define a method on a constructor
Instance methods and static methods :
Example method : Methods that must be child objects of this type can be called
such as : arr.sort() arr.push()
when : As long as a child object of this type is required to be called
how : All methods placed in prototype objects are instance methods
Static methods : There is no need to create child objects of this type , Methods that can be used by any object .
such as : Array.isArray(fun)


when : When you are not sure what type of object the function will be called in the future
how : Methods added to constructor objects are static methods . Can be done through constructor . Static method directly calls !

31. polymorphic :

What is? : A method shows different states in different situations
Include :

  1. heavy load overload:
  2. rewrite override:
    What is? : If a child finds it difficult to use a member inherited from its parent , Self owned members with the same name can be defined locally , Override the member of the parent object
    Why? : Members inherited from the parent object are not easy to use
    when : As long as members inherited from the parent object are not easy to use
    how : Define own members with the same name locally

32. Custom inheritance :

  1. Only modify the parent of an object

  2. Modify the parent of all child objects :
    Constructors .prototype=father
    opportunity : Replace before creating sub objects !

  3. Inheritance between two types :
    when : When it is found that multiple types have part of the same attribute structure and method definition , All must abstract the parent type out
    how : 2 Step :

    1. Define abstract parent type : 2 Step :

      1. Define constructors to hold public attribute structures
      2. Define how prototype objects hold public
    2. Let the child type inherit the parent type : 2 Step :

      1. Borrow a supertype constructor in a subtype constructor
        error : Call directly : Flyer(fname,speed)
        reason : Flyer no need . no need new call , Among them this Default finger window,Flyer All attributes in are leaked to the global level
        correct : use call Will be right this Injection into Flyer in , Instead of the wrong this
        how : Correct this, fname,speed)
      2. Let the child type prototype object inherit the parent type prototype object
        Object.setPrototypeOf( Subtype prototypes , The supertype prototype )


  1. Strict mode :
    What is? : Better than average js The operating mechanism requires a more stringent model
    Why? : ordinary js There are many widely criticized flaws in the operating mechanism
    when : In the future, all projects must run in strict mode

    1. If a new project , Whole js File enable strict mode
    2. Old project , Enable strict mode function by function

how :

  1. stay script Or the whole js Top of file , add to "use strict";
  2. At the top of the function , add to "use strict";

The rules : 4 individual :

  1. Do not assign values to undeclared variables
  2. Upgrade silent failure to error
  3. In the self-tuning of ordinary or anonymous functions this Default no longer points to window, It is undefined
  4. No use arguments, arguments.callee,…

repair : arguments.callee Automatically get the function itself that is currently being called
Ban , Recursion is strongly not recommended !

34. The object of protection :

Protect the properties of the object :
ES5 Divide object properties into :
Named properties : You can use . Directly accessed properties
Data attribute : Properties that store property values directly
Protect data properties : 4 Big characteristic :

 An attribute contains four features :{
value: Actual save property value ,
writable: true/false, // read-only
enumerable: true/false, // Non traversal
// It's not completely hidden , use . Still accessible !
configurable:true/false //1\. It is forbidden to delete
//2\. Do not modify other features
// Once it's changed to false, Irreversible
Get the four features of an attribute :
var attrs=Object.getOwnPropertyDescriptor(obj," attribute ")
Modify four features :
Object.defineProperty(obj," attribute ",{
Four characteristics : value
Abbreviation : Object.defineProperties(obj,{
Property name :{
characteristic : value ,
characteristic : value ,
Property name :{
... : ...

Accessor properties : Do not store attribute values directly , Only provides protection for another data property
when : Just provide custom rule protection for an attribute
how :

 add to : Only use Object.defineProperty and defineProperties add to
Four characteristics : {
get(){ return this. Data attribute }
If you verify val adopt
this. Data attribute =val
Report errors

How to use : It's the same as normal data attribute usage !

 When the value is taken , Automatically call the get
When assigning value , Automatically call the set Method , At the same time, the new value to the right of the equal sign , hand val Parameters

problem : enumerable We can only prevent for in, I can't help it ., Still available . Modify protected data properties directly
solve :
Internal attributes : Out-of-service . Directly accessed properties
such as : class proto

Protect the structure of the object : 3 Kind of

    1. Anti expansion : Prohibit adding new properties to objects
      principle : Internal attributes : extensible:true

      preventExtensions take extensible Change it to false
    2. seal up : While preventing expansion , Disable deleting existing properties
      principle : 1. take extensible Change it to false, No extension

      2. Automatically put all attributes of configurable All changed to false
    3. frozen : While sealing , Do not modify all property values
      principle : 1. It has all the functions of sealing

       2. And then add the... Of each attribute writable Automatically change to false!
  1. Object.create()
    Use only the parent object , You can create sub objects ,
    At the same time, it can also extend its own attributes for sub objects
    var child=Object.create(father,{
    Property name :{

     characteristic : value ,
    characteristic : value ,

    despise : describe Object.create Implementation principle of

    1. Create an empty object child
    2. Automatic setting child Of __proto__ by father
    3. by child Extend new own attributes

Replace what is not expected in the function this!
call/apply: Call the function now , And temporarily replace the this For the specified object
when : As long as the function is called , Function this Don't use what you want call Change to what you want
If the parameter of the incoming function , It's in the form of an array , The whole is introduced into
Just use .apply(obj,arr)
bind: Based on the original function , Create a new function , And permanently bind this For the specified object
when : Functions that are not called immediately ( Callback function ) Medium this, It's not what you want , You can use bind Create a new function , And permanently bind this!

36. Array API:

Judge :

  1. Determine whether all elements in the array meet the conditions

    //elem: Current element value
    //i: The current position
    //arr: Current array object
    return Judge the condition


  2. Determine whether the array contains elements that meet the conditions

    return Judge the condition


Traverse :

  1. forEach: Perform the same operation on each element in the original array
    arr[i]= The new value
  2. map: Take out each element in the original array and perform the same operation , Put the new array . The original array remains the same,i,arr){
    return The new value

Filter and aggregate :

  1. Filter : Copy the elements that match the conditions in the original array , Put in a new array to return
    var subs=arr.filter(function(elem,i,arr){
    return Judge the condition
  2. Summary : Count all the values in the original array to get a final conclusion
    var result=arr.reduce(function(prev,elem,i,arr){
    //prev: Up to now , The previous provisional aggregate value
    return prev+elem;

37.let: Instead of var

problem 1: A statement in advance , Destroy the original execution order of the program
solve : let No prior to the declaration , Use the variable in advance
problem 2: js There is no block-level scope , Variables within a block , It will contaminate the outside of the block
solve : let Will put the current if/for/while…(){} To block level scope

 consequence : In block let The variables will not affect the external !

principle : Actually let It's anonymous function self tuning !
let And for loop , Can form the effect of closure
emphasize : Variables that can be used both inside and outside the block , There's a piece , It can't be used !

38. Parameter enhancement :

The default value is : function fun( Parameters 1, Parameters 2,…, Parameters n= The default value is )
emphasize : The default value must be defined at the end of the list
principle : Parameters n= Parameters n|| The default value is ;
rest: Instead of arguments
when : Function as , When the number of parameters is uncertain —— heavy load
Why? : arguments The shortcomings of :

  1. Class array object , Is not an array
  2. Only after all , Can't have a selection of segments to get

how : When defining a function : function fun( Parameters 1, Parameters 2,…, … Array name )
Array name , It's a pure array , And it can be segmented selectively
principle : var arr=[][,starti]);// Convert class array objects to arrays
spread: Instead of apply
Why? : apply Although the array type parameter can be broken to a single value , But it has to be replaced this The operation of is bundled with
when : As long as you only need to scatter the array type parameter to a single value
how : Invocation time : fun( Parameter values 1, Parameter values 2,… Array )

  1. Arrow function : Instead of... In the callback function function

when : As long as the callback function , No longer use function, Instead, use the arrow function
how :

  1. Go to function Change =>

  2. If there is only one parameter , Omission ()

  3. If there is only one sentence in the function body , be {} Omission

     More simplified : If the only sentence is still return, Omission return

characteristic : Inside and outside share the same this —— Instead of bind
problem : If instead, you want to be inside and outside this When not in use , You can't use the arrow function

40. Template string : Instead of + Number concatenation string

ESLint Regulations , Not allowed + String concatenation
how :

  1. Define templates : Left and right template content must be placed in `` in
  2. Embed a variable or expression in a template , Dynamically generate content :
    In formwork , You can use ${…} Embed any legal js A variable or statement

41. deconstruction : Simplify batch assignment

What is? : Put an object / Members and elements in the array , Separate them out , Use alone .
Why? : Avoid reuse of object names / Array name
when : As long as you want to take out a large object or each member of an array separately
how : 3 Kind of :

  1. An array of deconstruction : Subscript to subscript
  2. Object to deconstruct : Attribute to attribute
  3. Parameters of deconstruction : Attribute to attribute
    When defining a function :
    problem : The order and number of arguments in a common function are fixed
    solve : Use object syntax to define parameter lists
    advantage : Number of parameters passed in in the future , The order has nothing to do with the list of objects
    Call function : Also use object syntax to pass in parameters
    In the process of assignment , The way of adopting object structure , Assign a value to a parameter variable

42.for…of In certain circumstances , Instead of for loop

What is? : Traverse the array in turn / The value of each element in the class array object
vs for…in: Traverse the associative array in turn / The property name of each member in the object
when : If you want to traverse the entire array or class array object from the beginning to the end
how :

for(var elem of arr){

limited : Unable to get current position ; Can't control the progress of traversal / The order ; There is no alternative traversal part

43.class: Instead of traditional packaging , Inherit , Polymorphic grammar

encapsulation :

 class Student {
... ...
intr (){//Student.prototype.intr
fun (){

Inherit :

 class Flyer {
... ...
fly (){
... ...
class Plane extends Flyer{
//super Point to parent type constructor , And automatically replace this
... ...
getScore (){
... ...

Static methods :

 class User{
save(){// Save in User.prototype Example method in
console.log(" Save the current object ");
static findOne(){// Static methods , Defined on the constructor
return new User();
var user=new User(...);;// Invoking an instance method
User.findOne();// Call static methods

44.Promise: solve : Back to hell

What is? callback hell: Because the callback function is passed with parameters , Lead to many steps , Parameters are deeply nested .
when : Just call it asynchronously , When delays may occur , You have to use Promise Instead of traditional parameters callback
how : Definition time

 function The first thing (){
return new Promise(fn=>{
The first thing
function The second thing (){
return new Promise(fn=>{
The content of the second thing
function The third thing (){
The third thing
web Front end development live tutorial Q-q-u-n: 767273102 , There are free development tools for rice , Zero basis , Advanced video tutorial , I hope novices don't take detours

Invocation time :

 The first thing ()//return Promise(fn)
.then( The second thing )//return Promise(fn)
.then( The third thing )

Disdain the question :

  1. Copy the class array object as an array :
    Copy the class array object as an array , And select the remaining elements at the specified location
    var arr2=,starti)

     amount to arguments.slice(starti)

    Actually, it's simpler : var arr2= [],starti)

  2. promise Error handling in :
    Actually : new Promise( Acceptable 2 thing )

    .then( ) .catch( )

    new Promise(( Normal function , Error function )=>{

     If it goes well :
    Call OK ()
    Call error ()


  3. Waiting for multiple tasks to complete
    Premise : Every task has to return Promise
    how : Promise.all([

     task1(), task2(),...
    ]).then(()=>{ Tasks performed after all tasks have been completed })

本文为[JavaScript language]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple