This is the first day of my participation in the August Challenge. For details, see:August is more challenging

Recently in preparation for autumn recruitment interview, followed a lot of predecessors and big guys public number, also read the nuggets in many big guys front end of the article, very useful to me, I put them down below, so that they can further study.

Draught does not forget to dig the well, thank you again, each big guy’s article I will do a summary one by one in the following

1.JS data types and storage methods

Answer: Js has 7 primitive data types and 1 reference data type

    // Raw data type
    null
    undefined
    Boolean
    Number
    String
    Symbol(new) ES6BigInt
    // Reference the data type
    Object
    /* Object contains: normal Object Array regular Object RegExp Date Function Math Function Function */
Copy the code

Storage: Raw data types are stored in stack memory, and reference data types are stored in both stack memory and heap memory (reference type Pointers are stored in stack, and stored Pointers point to the starting address of data in heap memory)

2.JS data type judgment

1. Use typeof judgment

Disadvantages: The original data type is null and the reference data type except Function is Object

    typeof 1 //'number'
    typeof '1' //'string'
    typeof undefined //'undefined'
    typeof true //'boolean'
    typeof Symbol(a)//'symbol'
    
    typeof [] //'object'
    typeof {} //'object'
    typeof console.log() //'function'
Copy the code

2. Use instanceof

Disadvantages: Cannot accurately determine the original data type, only the reference data type can be determined

Principle: Instanceof determines whether the prototype of an object can be found in the prototype chain

    1 instanceof Number //false
    true instanceof Boolean //false 
    'string' instanceof String //false  
    
    [] instanceof Array //true
    console.log() instanceof Function //true
    {} instanceof Object//true    
Copy the code

3. The use of the Object. The prototype. ToString. Judgment call ()

    Object.prototype.toString.call(1) //Number
    Object.prototype.toString.call(true) //Boolean
    Object.prototype.toString.call('string') //String
    Object.prototype.toString.call(Symbol()) //Symbol
    Object.prototype.toString.call(null) //null
    Object.prototype.toString.call(undefined) //undefined
    Object.prototype.toString.call([]) //Array
    Object.prototype.toString.call({}) //Object
    Object.prototype.toString.call(console.log()) //Function
Copy the code

3. Difference between null and undefined

Both null and undefined are basic data types in Javascript. Undefined means that the variable should have a value but is not defined, and NULL means that it should not.

4. The difference between == and ===

=== is a strict operator, and == is an equality operator

1. Strict operator comparison rules

  • Compare different types: different types return directlyfalse
  • Same type (raw data type) : Return if the values are equaltrue, do not want to wait to returnfalse
  • Same type (reference data type) : refers to the same objecttrueOtherwise returnfalse

2. Equality operator comparison rules

  • Raw type comparison: All data are converted to numeric types and compared

  • Object to primitive type comparison: The object is compared after being converted to a value of the primitive data type

  • Implicit conversions exist in the equality operator

    What is worth mentioning is the comparison between null and undefined.

    null= = =undefined //false
    null= =undefined //true
Copy the code

5. The prototype chain

Here’s an article that’s easy to understand: “You Need to Understand Prototypes and Prototype Chains, whether you’re interviewing or not” by Nick Chen. Here’s a picture of Nick Chen’s above article and a classic prototype chain picture. An object’s __proto__ refers to its prototype. prototype, up to null. Its prototype. constructor refers to its prototype. prototype


6. Js inheritance

ECMAScript only supports implementation inheritance and relies heavily on prototype chains. The inheritance of Js includes prototype chain inheritance, borrowing constructor inheritance, combination inheritance, original type inheritance, parasitic inheritance, parasitic combination inheritance six. This article writes about two types of inheritance: composite inheritance and parasitic composite inheritance

Composite inheritance (prototype chain inheritance + constructor inheritance)

    // Define the constructor
    function Parent(age){
        this.age = age
    }
    // Set the Parent method
    Parent.prototype.sayAge = function(){
        console.log(this.age)
    }
    // Define the Child and use the constructor to inherit the age property of Parent
    function Child(age){
        Parent.call(this,age)
    }
    // Inherit Parent's sayAge method through the prototype chain
    Child.prototype = new Parent()// The constructor is called once
    // Create the Child instance
    const childInstance = new Child(18)
    console.log(childInstance.age)/ / 18
    console.log(childInstance instanceof Parent)//true
Copy the code
  • Advantages: Parent methods are reusable, constructors are passable, inherited attributes are not shared
  • Disadvantages: Unnecessary properties in the superclass, wasted memory, two constructor calls

Parasitic combination inheritance

  • Parasitic combination inheritance optimizes combination inheritance, makes up for the shortcoming of calling the constructor of the parent class when inheriting the parent class, and avoids unnecessary attributes
  • Principle: In inheritance, there is no inheritance of the parent classInstance objectsSo that there is no call to the parent classThe constructor, but inheritedThe instance object of the prototype of the parent objectTo avoid unnecessary attributes generated during inheritance
  • Method: Modifying the prototype
    // Define the constructor
    function Parent(age){
        this.age = age
    }
    // Set the Parent method
    Parent.prototype.sayAge = function(){
        console.log(this.age)
    }
    // Define the Child and use the constructor to inherit the age property of Parent
    function Child(age){
        Parent.call(this,age)
    }
    // Modify the prototype chain
    const prototype = object(Parent.prototype)
    prototype.constructor = Child
    Child.prototype = prototype
    // Create the Child instance
    const childInstance = new Child(18)
    console.log(childInstance.age)/ / 18
    console.log(childInstance instanceof Parent)//true
Copy the code

7. Event dissemination

When an event occurs on a DOM element, it doesn’t just happen on that element. Instead, it starts with window and works its way up to the specified element. Event propagation has the following three stages:

  • Capture phase: Event fromwindowThe trigger starts at a level that escalates inward until it reaches the specified element
  • Target phase: The event has reached the target element
  • Bubble phase: Events bubble from the target element to the outer layer, layer by layer untilwindow

8. The useCapture parameter of addEventListener

The third optional argument to the addEventListener method is useCapture, which defaults to false. When false, the listener event is emitted during the event bubble phase, and when true, the listener event is emitted during the capture phase

9. Event capture

When an event occurs on a DOM element, it doesn’t just happen on that element. Instead, it starts with window and works its way up to the specified element. Event capture phase, events are: window→document→ HTML →body→ specified element

10. Event delegation

Event delegation essentially takes advantage of the event bubbling mechanism. Events in the process of bubble, uploaded to the parent node, the parent node at the same time can also through the event object positioning to the target child nodes, so the child nodes monitor events can be defined in the parent node, so that you can by a parent to monitor all child nodes under the parent node of events without the need for each child node binding to monitor events, also known as event agent. Event agents reduce memory consumption and enable dynamic binding of events.

11. New ES6 features

  • Block scope
  • class
  • Template string
  • Object to deconstruct
  • Arrow function
  • The module
  • Enhanced literal objects
  • Default function arguments
  • Promise
  • Symbol
  • set
  • proxy
  • rest

12. Arrow function features

  • There is no definition context of its own
  • thisAlways pointing to the outer layerthisNot inside the arrow function
  • Cannot be used as a constructor (cannot be usednew)
  • There is noarguments

13.Set, WeakSet, Map, WeakMap

1.Set

Features:
Element order Elemental repetition Storable type
A disorderly Do not repeat Raw data type + reference data type

Set Set

    let set = new Set(a)/ / create the Set
    set.add(0)
    set.add(1)
    set.add(2) // Add the element
    set.delete(2) // Delete the element
    set.forEach(item= >{
        console.log(item) / / 1, 2
    }) / / traverse
    set.has(1) // Check whether the collection contains an element,true
    set.clear() // Clear the collection
Copy the code

In addition, the reference objects in the Set object have been strongly typed, and can not automatically reclaim useless reference objects, which will cause memory waste, and the cost of recycling is high, WeakSet solves this problem

2.WeakSet

Features:
Element order Elemental repetition Storable type
A disorderly Do not repeat Reference data type
  1. WeakSetOnly reference objects can be stored, otherwise they will be thrownTypeErrorerror
  2. WeakSetCannot contain objects without references (null), otherwise the object will beAutomatically reclaim (move out of the collection)
  3. WeakSetObjects stored inAn enumerationThat is, it cannot be obtainedWeakSettheThe size of theAnd one of theThe element

Related code:

    let weakset = new WeakSet(a)let foo = {}
    weakset.add(a)
    console.log(... weakset)//Exception is thrown
    console.log(weakset.size) //undefined
    weakset.clear() // There is no such method
    // A method to remove an object and check whether elements in the object exist
    console.log(weakset.has(a)) //true
    foo = null // Automatically reclaim objects without references
    console.log(weakset.has(a)) //false
Copy the code

3.Map

Features:

A Map is similar to an object in that it is a collection of key-value pairs, but unlike a traditional object, only values of type Number, String, or Symbol can be used as key names. A Map can be used as key names of any type

Advantages of using Map:

  • The same size of memory,MapMore storage
  • throughsizeTo obtainMapThe length of the

Related methods:

    / / base
    let map = new Map()
    map.set("tony".21)
    map.set("steve".22) // Add key-value pairs
    console.log(map.get("tony")) // Find value by key, 21
    console.log(map.has("tony")) // Check whether the key contains an element, true
    console.log(map.delete("steve")) // Delete elements by key, true
    console.log(map.has("steve")) //false
    // Iterate over the method
    let m = new Map([["tony".21],
        ["steve".22]])for(let key of m.keys()){
        //keys() gets the iterator for all keys in the Map
        console.log(key) 
        // "tony"
        // "steve"
    }
    for(let value of m.values()){
        //values() Gets a traverser for all values in the Map
        console.log(value)
        / / 21
        / / 22
    }
    //entries() Get all Map key-value pairs iterator
    for(let item of m.entries()){
        // Normal writing
        console.log(item)
        // ["tony",21]
        // ["steve",22]
    }
    for(let [key,value] of m.entries()){
        // Deconstruction
        console.log(key,value)
        // "tony" 21
        // "steve" 22
    }
Copy the code

4.WeakMap

Features:

The characteristics of WeakMap

  • Only receive objects askey(nullExcept)
  • keyIs the weak reference referred tovalueCan be recycled after recyclingkeyIt’s invalid. Members can disappear at any time
  • Does not supportMapGets the traverser in the

14.Proxy

Concept: Proxy can be understood as a layer of “interception” set up before the target object. All external access to the object must pass through this layer, so it provides a mechanism to filter and rewrite external access.

15. This point

Here’s an image from Jake’s blog post, from the basics to the Basics: 66 JavaScript Interview Tips

The picture is very detailed and clear:

  • At the global scope,thisPoint to thewindow
  • In a function, this always refers to the object that last called the function
  • In the constructor, this refers to the instance that was created by new
  • In call, Apply, and bind, this refers to the object to be bound
  • This in the arrow function always points to this in the parent scope

16. How is new implemented

New = new = new = new = new = new = new = new = new = new = new = new

After new is used, the following steps are performed:

  1. Create an empty objectObject({})
  2. Link the empty object to another object (requirednewObject) (link to the constructor)
  3. Treat the newly created empty object asthiscontext
  4. return

Here’s a snippet of code from Jake’s blog post: From the basics to the Basics: 66 JavaScript Interview Tips

    function Dog(name, color, age) {
      this.name = name;
      this.color = color;
      this.age = age;
    }

    Dog.prototype={
      getName: function() {
        return this.name
      }
    }

    var dog = new Dog('rhubarb'.'yellow'.3)
Copy the code

Part of the analysis code is as follows:

    // Step 1: Create a simple empty object
    var obj = {}
    // Step 2: link the object to another object (prototype chain)
    obj.__proto__ = Dog.prototype
    // Step 3: Use the new object created in Step 1 as the context for 'this'. This refers to the obj object
    Dog.apply(obj, ['rhubarb'.'yellow'.3])
    // Step 4: Return this if the function returns no object
    
    // Because Dog() does not return a value, obj is returned
    var dog = obj
    dog.getName() // 'rhubarb'

    // Return the value of return if Dog() has a return
    var rtnObj = {}
    function Dog(name, color, age) {
      // ...
      // Return an object
      return rtnObj
    }

    var dog = new Dog('rhubarb'.'yellow'.3)
    console.log(dog === rtnObj) // true
Copy the code

17. Scope and scope chains

  • Scope: The area in which variables are defined. It has a set of rules for accessing variables that govern how the browser engine looks for variables in the current or nested scope
  • Scope chain: ensures orderly access to the browser engine within the scope. In simple terms, variables that cannot be found in the inner scope are searched out, like a chain
  • Scope: nature is actually a pointer to the variable list, the variable object contains all the variables and functions in the execution environment, that is to say, the pointer list is contained in every context, from the inside out of the variable object, global scope of the variable object is the pointer to the last in the list of objects

When looking for a variable, if it is not found in the current execution environment, it is looked back down the scope chain

Var, let, const

  • varThere are variables that are risingletandconstThere is no
  • letandconstThe declaration forms a block scope. No variable can be found outside the scope
  • In the same scopevarThe ability to repeatedly declare variables whileletandconstCan’t
  • constThe assignment must be made at declaration time, if the assignment isBasic data type, cannot be modified. Otherwise, an error will be reportedReference data type(object), cannot be modifiedconstObject, but properties in the object can be modified

19. Temporary dead zone

In a block scope, if a variable is declared as let and const, it will only be found in the scope of the block, even if the same variable exists outside the scope of the block. Therefore, we have the following code:

var a = 100;
if(1){
    a = 10;
    // If a is declared let/const in the current scope, if a is assigned 10, then only a is found in the current scope.
    // Error:a is not defined
    let a = 1;
}
Copy the code

20. Closure

In a nutshell: a closure is a function that has permission to read variables inside the scope of another function

Common use:

  • Creating a private variable
  • Store the context variables at the end of the run in memory

Example code:

    // Common usage
    function a(){
        var b = 0;
        function c(){
            console.log(b)
        }
        return c
    }
    const testc = a()
    testc()
    // Private variables
    function person(name,age){
        var name = name
        this.age = age
        this.getName = function(){
            return name
        }
    }
    const tony = new person('tony'.21)
    console.log(tony.name) //undefined
    console.log(tony.age) / / 21
    console.log(tony.getName())//tony
Copy the code

You can think of closures as being generated when a function declaration is created. You can think of the game character as having a backpack that contains the lexical scope of all variables in the execution context of the function. For more details, see Medium’s fifty thousand Praise essay – “I’ll Never Understand THE JS Closure” by Nuggets Anthony.

21.JS running mechanism

Javascript is single-threaded, depending on its purpose. Javacript’s main purpose is to interact with users and manipulate the DOM, so it can only be single-threaded. For example, if Javascript has two threads, one that does DOM add and the other that does DOM delete, there will be a contradiction.

22. Macro and micro tasks

  • Macro task:The whole script,setTimeout,setInterval,setImmediate
  • Micro tasks:Promise,process.nextTick,MutationObserver

23. Event loop

Let’s start with a personal understanding of the event cycle: In this macro task, if synchronous task is found, it will be executed immediately. If asynchronous task is found, it will be mounted (macro task is mounted to the Event Queue of macro task and microtask is mounted to the Event Queue of microtask). After completing these steps (completion of the macro task), it is considered that one round of Event loop has been performed. After this round of Event loop, it enters the Event Queue to check whether there is any mounted microtask. If there is, it will be executed. Looking for macro tasks in the Event Queue continues the work of executing code, mounting macro tasks, microtasks, and so on.

Continue: macro task → microtask mounted by the previous macro task → macro task mounted by the previous macro task → loop

Personal opinion, learning may not be very deep, if there are mistakes, very grateful for your corrections

Here’s some code:

    /* Output: 1.script start 2.script end 3.promise1 4.promise2 5.setTimeout */
    console.log('script start');

    setTimeout(function() {
      console.log('setTimeout');
    }, 0);

    Promise.resolve().then(function() {
      console.log('promise1');
    }).then(function() {
      console.log('promise2');
    });

    console.log('script end');
Copy the code

24.Promise

  • Three states:pending,fulfilled,rejected
  • Features: Status once frompendingChange to other states, is immutable
  • Role: SolveThe callback hellProblems in a way,Synchronous operationwayAsynchronous operations
  • Disadvantages: Cannot cancel, cannot get progress

This is very depressing. This is very depressing. This is very depressing, which is very depressing. My leader said I have to work overtime because of a new project, so I can’t ask you any more. According to this state, we have a new plan and plan to meet again next week, which is in the state of Rejected.

My understanding: In the last story, this Promise is a Promise. My Promise makes the Promise enter the pending state. When I fulfill the Promise, I will pay for dinner and work overtime, which makes the Promise enter different states respectively. Once the state becomes fulfilled or rejected, the Promise will be resolved and cannot be changed. With resolve, we have a new plan, which is equivalent to using the callback function to get the result and act accordingly

This will be fulfilled: Promise→pending→fulfilled or rejected→ return the callback function which will be fulfilled or rejected→ proceed to the next operation

25. Promise. All with Promise. Race

Promise.all

  • Application: Merge requests
  • Parameters:PromiseObject composedAn array of
  • Feature: Pass in arrays, multiplePromiseIf all the commands are executed successfully, the system returns successThe callback functionIf any of them fails to be executed, the operation fails
  • Function: Perform multiple asynchronous operations in parallelThe callback functionAll results are processed in
  • Understand: Complete all incomingPromise, all successfully returnedSuccessful callback function, returns if any failure occursFailed callback function
  • To execute slowlyPromiseLord, the last onePromiseAfter it’s overThe callback
    let Promise1 = new Promise(function(resolve, reject){})
    let Promise2 = new Promise(function(resolve, reject){})
    let Promise3 = new Promise(function(resolve, reject){})

    let p = Promise.all([Promise1, Promise2, Promise3])

    p.then(funciton(){
      // Success is when all three succeed
    }, function(){
      // If there is a failure, it will fail
    })
Copy the code

Promise.race

  • Application: Request timeout processing
  • Parameters:PromiseObject composedAn array of
  • Feature: Pass in arrays, multiplePromiseIf one of themPromiseChange the state first, thenPromise.raceReturns thePromisetheThe callback function
  • Function: Resolves timeout issues
  • To execute fastPromiseMain, returns thePrmiseThe operation of theThe callback
    const p = Promise.race([
      fetch('/resource-that-may-take-a-while'),
      new Promise(function (resolve, reject) {
        setTimeout(() = > reject(new Error('request timeout')), 5000)})]); p .then(console.log)
    .catch(console.error);
Copy the code

Race Performs the two asynchronous operations in the parameters. After 5 seconds, the timer triggers the asynchronous operations. P returns the reject callback function, indicating that the request times out

26. Async and await

  • Advantages: More readability, more concise code
  • Feature: if a function is preceded byasync, returns onePromiseIf, in theasyncInside the function, let’s writereturn, the function returns directlyPromise.resolve()
  • Note:awaitOnly in theasyncFunction

The following code is posted, using Promise and async/await, respectively

    // The initial code
    function takeLongTime(n) {
        return new Promise(resolve= > {
            setTimeout(() = > resolve(n + 200), n);
        });
    }

    function step1(n) {
        console.log(`step1 with ${n}`);
        return takeLongTime(n);
    }

    function step2(n) {
        console.log(`step2 with ${n}`);
        return takeLongTime(n);
    }

    function step3(n) {
        console.log(`step3 with ${n}`);
        return takeLongTime(n);
    }
    / / Promise
    // step1 with 300
    // step2 with 500
    // step3 with 700
    // result is 900
    function doIt() {
    console.time("doIt");
    const time1 = 300;
    step1(time1)
        .then(time2= > step2(time2))
        .then(time3= > step3(time3))
        .then(result= > {
            console.log(`result is ${result}`);
        });
    }
    doIt();
    / / async/await
    async function doIt() {
        console.time("doIt");
        const time1 = 300;
        const time2 = await step1(time1);
        const time3 = await step2(time2);
        const result = await step3(time3);
        console.log(`result is ${result}`);
    }
    doIt();
Copy the code

27. Async and defer in script tag

Common use:

    <script src='xxx'></script>
    <script src='xxx' async></script>
    <script src='xxx' defer></script>
Copy the code
  • Async:An asynchronous requestScript, if requested, pauseHTMLTo perform the parsing of the obtainedJavascriptCode before continuing parsingHTML
  • Defer:An asynchronous requestScript, if the request is received, wait firstHTMLWhen parsing is complete, execute the obtainedJavascriptcode

Disadvantages of async: The timing of obtaining the script is uncertain. When obtaining the script, some DOM elements have not been parsed and may not be obtained by the script. And if there are more than one async, then the script is not controllable

For more details, see the async and defer properties in the Graphical Script tag

28. JS precompiled

Order: global precompile → function body precompile

  1. Function body precompile
  • To create aAOObject (activation object)
  • Looking forparameterAs well asVariable declarationsThat will beparameterAs well asVariable declarationsAs newAOThe object’sattribute
  • willparameterwithThe argumentsunified
  • Looking forFunction declarationThat will beThe function nameAs aAOThe object’sattributetheattributeThe value ofThe body of the function
  • Functions are executed line by line (if a line of code existsVariable ascensionIgnoring it,The assignmentDon’t ignore)

Step summary: create empty AO object → add variable declaration, parameter to AO object → parameter, argument unity → add function declaration to AO object → execute function line by line

    function fn(a) { 
      console.log(a); //function a() {}
      var a = 123; / / assignment
      console.log(a); / / 123
      function a() {} // The variable has been promoted, ignore
      console.log(a); / / 123
      var b = function() {} 
      console.log(b); //function() {} 
      function d() {} 
      var d = a / / assignment
      console.log(d); / / 123
    }
    fn(1)
    AO:{a:undefined b:undefined d:undefined} 3. {a:undefined b:undefined D :undefined} 3. AO:{a:1 b:undefined D :undefined} 4. AO:{a:function(){} b:function(){} d:function(){}} 5 Using AO objects, step by step according to the code inside the function (the variable promotion part is ignored, but the assignment part is not ignored) */
Copy the code
  1. Global precompile
  • createGOObject (global object)
  • Looking for aVariable declarations, declare the variable asGOObject attribute name, value assigned toundefined
  • Looking for aIn the globaltheFunction declarationThat will beThe function nameAs aGOThe object’sThe property name.The body of the functionAs theattributethevalue

Step summary: create empty GO object → add variable declaration GO object → add function declaration to GO object → execute function line by line (global before function body)

    1:global = 100 // Assignment, not declaration
    2:function fn() {
    3:   console.log(global); // undefined
    4:   global = 200
    5:   console.log(global); / / 200
    6:   var global = 300
    7:}
    8:fn()
    GO:{} 2; GO:{} 3 GO:{} 3 GO:{} 3 GO:{fn:function fn() {console.log(global); // undefined global = 200 console.log(global); // 200 var global = 300}} Create an empty AO object AO:{} 2. Find the variable declaration and parameter, write AO{global:undefined} 3. AO{global:undefined} 4 (AO{global:undefined}); (AO{global:undefined}); (AO{global:undefined}); In the first line, the global variable is assigned, and there is no global in the GO object, so a global variable is declared with a value of 100 and 2 is written to the GO object. 3. In line 3, global is undefined in the AO object, so undefined 4 is output. In line 4, global is set to 200 5. In line 5, global is set to 200 6. In line 6, assign global to 300 (steps 3, 4, 5, and 6 are all handled in AO objects) */
Copy the code

29. Differences between AMD, CMD, Module and CommonJs

Differences between AMD and CMD:

  • AMDTo promoteDependencies are front-loaded and executed ahead of time, i.e.,defineThe dependent modules passed in the method are downloaded and executed at the outset (declared when the module dependencies are defined)
  • CMDTo promoteRely on proximity, delay executionIn which therequireDepends on the module (on demand)
  • commonAMDSpecification: RequireJs
  • commonCMDSpecification: SeaJs

Here is a piece of code from JakeZhang

    // CMD
    define(function(require.exports.module) {
      var a = require("./a");
      a.doSomething();
      // Omit 100 lines here
      var b = require("./b"); Dependencies can be written nearby
      b.doSomething();
      // ...
    });

    // AMD's default recommendation
    define(["./a"."./b"].function(a, b) {
      Dependencies must be written from the start
      a.doSomething();
      // Omit 100 lines here
      b.doSomething();
      // ...
    });
Copy the code

CommonJs and ES6Module:

Relation to dependence:

  • CommonJsThe establishment of modules and dependencies occurs during the code run (dynamic)
  • ModuleModule and dependency creation occurs during code compilation (static)

Nature and Characteristics:

  • CommonJsThe output is a copy of the value (the output is no longer affected), whereas in ES6ModuleThe output is a reference to a value (that is, a binding to a variable)
  • CommonJsOnly a single module can be exported, whileModuleCan export multiple

Operating mechanism:

  • In the ES6ModulewithCommonJsWhen the Js engine performs static analysis on the script, if there isimport, generates oneRead-only referenceWhen the script is actually executedRead-only referenceLoad the module and get the value (importI can only write at the top, andCommonJsUnlimited)
  • CommonJsMechanism isRuntime loading.CommonJsA module is an object, that is, after a module is loaded, an object is generated, and then methods are read from that objectRuntime loading

30.Js garbage collection mechanism

Js garbage collection two strategies:

  • Mark recycling
  • Reference counting

Mark recycling

  • Tag collection is the most common garbage collection mechanism in browsers. When the variable goes inThe execution environment, the variable is marked asInto the environmentAnd left thePerform linkIs marked asLeave the environmentIs marked asLeave the environmentThe variable is freed from memory
  • Garbage collector (GCAll variables stored in memory are marked at runtime. Then, it will remove the rightThe execution environmentAfter that, the marked variables will be collected. The garbage collector completes the memory cleaning work, destroying the marked variables and reclaiming the memory occupied by them

Reference counting

  • A reference count is a record of each valueThe number of times it was referenced, when a variable is declared and aReference type valueWhen assigned to the variable, the valuecitationsadd1. Conversely, if the variableIs assigned to another value, then the valuecitationsReduction of1When the valuecitationsfor0, indicating that the value is alreadyNo use value, the value of this value at the time of collectionmemoryIt will beThe release of
  • Existing problems: May causeA circular reference. For example, in the following code,obj1withobj2By referring to each other through attributes, when the execution is complete,obj1,obj2leftscope, butobj1,obj2The number of references is not0Is not automatically reclaimed, resulting inA circular reference(the function is incremented by 1 each time it is run), and memory needs to be reclaimed manually.
    // For each call, the number of references is incremented by one, never zero
    function fun() {
        let obj1 = {};
        let obj2 = {};
        obj1.a = obj2; // Obj1 references obj2
        obj2.a = obj1; // Obj2 references obj1
    }
    // Manually reclaim memory
    obj1.a =  null
    obj2.a =  null
Copy the code

Ways to reduce garbage collection

When the code is more complex, the cost of garbage collection will be relatively large, so garbage collection should be minimized as follows:

  • rightAn array ofOptimize: Set the array manuallyThe length of the0
  • rightobjectOptimize:objectReuse as much as possible, if no longer in use, assign tonullTo make it recycled as soon as possible
  • rightfunctionTo optimize: if the circulation inside the bodyfunctionReusable, as far as possible in the circulation outside the body

31. Memory leak

Cause of memory leak:

  • Unexpected global variable: A global variable is accidentally created by using an undeclared variable
  • Forgotten timer (forgot to cancelsetInterval) or the callback function (which has a reference to an external variable) cannot be reclaimed
  • References outside the DOM: Get oneDOMThe element is deleted, but the reference to the element remains, which makes it impossible to reclaim
  • Unreasonable closures

32.IIFE(call function expression immediately)

Usage: The function is executed immediately after it is created

    (function IIFE(){
     console.log( "Hello!"); }) ();// "Hello!"
Copy the code

33. for.. In and for… The difference of

Iterating over objects:

  • for... ofGet the object key,for... inGets the object key name

Iterating over an array:

  • for... ofGet the array elements,for... inGet array index

The difference between:

  • for... inLoops are primarily for traversalobject, does not apply to traversalAn array of;for... ofLoops can be used to iterateAn array of,Arraylike object.string,Set,MapAs well asGeneratorObject.

34. XSS and CSRF

Cross Site Scripting (XSS), also known as cross-site Scripting, is a code injection attack

  • Principle: An attacker inserts malicious script code into a page. The user who uses the page runs the script. The attacker uses the script to obtain the user’s codeCookieAnd other sensitive information, jeopardize data security
  • Categories: stored (persistent, malicious code in the database), reflected (non-persistent, malicious code in the URL), DOM

XSS prevention:

  • HttpOnly:CookieSet in thehttpOnlyProperties,JavascriptScript cannot be obtainedCookieinformation
  • Input filtering: Check the input format to avoidJavascriptInput and upload related script code
  • The necessary escape of the input and output results

Cross-site Request forgery (CSRF), also known as cross-site request forgery

Here is a picture from the front interview: (7) XSS attack and CSRF Attack — shotCat

  • How it works: An attacker uses a dangerous website to use the victim’sCookieTo make it look like a dangerous operation by a user
  • Type: GET, POST, and link

The following code is posted from the same source:

    / / GET type CSRF
    <img src="http://bank.example/withdraw? amount=10000&for=hacker" > 
    / / after the victim to visit the page containing the img, the browser will automatically ` on to http://bank.example/withdraw? Account =xiaoming&amount=10000&for=hacker ' Bank.example will receive a cross-domain request containing the victim's login information.
    
    / / POST type CSRF
    <form action="http://bank.example/withdraw" method=POST>
        <input type="hidden" name="account" value="xiaoming" />
        <input type="hidden" name="amount" value="10000" />
        <input type="hidden" name="for" value="hacker" />
    </form>
    <script> document.forms[0].submit(); </script> 
    // After visiting the page, the form is automatically submitted, which is equivalent to a simulated user completing a POST. POST type attacks are usually a little more demanding than GET, but still not complicated. Any personal website, blog, and the website uploaded by hackers may be the source of the attack. The back-end interface cannot rely on the security of only allowing POST.
    
    // Link type CSRF
    <a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker" taget="_blank">Blockbuster news!!<a/>// The user clicks to trigger the requestCopy the code

Features:

  • Attacks are usually launched on third-party websites
  • Attackers use the login credentials of users to impersonate users, rather than directly steal data
  • During the whole process, the attacker cannot obtain the userCookieData, just a fraud
  • Attacks are usually cross-domain

Precautions against CSRF:

  • Use verification codes: prevent requests from being executed directly
  • Referer check: The request is not executed if the request source does not meet the requirements
  • Use token token: Verify that the token is correct on request

Differences between XSS and CSRF

  • XSS is to inject code to implement attacks, CSRF is to exploit usersCookieIllegal request Api to implement illegal operation
  • XSS attacks do not require user login, while CSRF attacks require user login

35. Add, delete, modify and check DOM nodes

    / / to find
    document.getElementById(id)
    document.getElementByName(name)
    document.getElementByClassName(className)
    document.getElementByTagName(tagName)
    / / create
    document.createElement("h1")
    document.createTextNode(String)// Create a text node
    document.createAttribute("class")// Create an attribute node
    / / delete
    element.removeChild(node)
Copy the code

How do I delete a DOM

Look at the code, source: CSDN

<body>
    <div id="main">
        <div id="box">111</div>
        <div class="box2">222</div>
    </div>
    <script type="text/javascript">
        var box = document.getElementById("box");
        var main = document.getElementById("main");
        var newMask = document.createElement("div");
        newMask.id ="newMask";
        main.appendChild(newMask); 
        if(box){
            box.parentNode.removeChild(box); / / in this
        }
        else{
            alert("There is no div.");
        }
    </script>
</body>
Copy the code

37. ForEach, map, find and filter

  • forEachThere is no substantial return, generally is the direct operation of the original array, andmapwithfilterWill allocate memory space to store the new array and return it, without affecting the original array,findReturns a callback function that does not affect the array
  • forEachUsage: Often used for display (only for traversing groups, no return value)
  • mapUsage: letAn array ofAccording to onefunctionAn array ofEach elementforThe corresponding operationandRebuild the arrayandreturn(Must have a return value)
  • filterUsage: letAn array ofAccording to oneThe rulesFor each of the arraysThe elementforscreeningandRebuild the arrayandreturn

Callback (arg1, arg2, arg3)

  • Arg1: Iterates over the resulting elements
  • Arg2: The element index obtained by traversal
  • Arg3: The array to iterate over

This code is from JavaScript Arrays (forEach, Map, Filter, Find) — itclanCoder:

//forEach
var obj = {
    "data": {"members": [{"id":111."name":"Gao"},
        {"id":222."name":"Xiao"},
        {"id":333."name":"Wang"}}}]var newArrs= [];
obj.data.members.forEach(function(member,index,originArrs){
newArrs.push(member.name);
})
console.log(newArrs); //[" Xiao Gao ", "Xiao Fan "," Xiao Wang "]

//map
var numbersA = [1.2.3.4.5.6];
var numbersB = []
var numbersC = numbersA.map(function(numberA,index,originArrs){
   return numbersB.push(numberA*2);
}
console.log(numbersA); / / [6]
console.log(numbersB);// [2, 4, 6, 8, 10, 12]
console.log(numbersC);// [1, 2, 3, 4, 5, 6]
console.log(numbersC==numbersA)  // false

//filter
var persons = [
{name:"Wang".type:"boy".city:"Guangxi".age:15.height:170},
{name:"Little beauty".type:"girl".city:"Beijing".age:16.height:180},
{name:"Gao".type:"girl".city:"Hunan".age:18.height:175},
{name:"Liu".type:"boy".city:"Hebei".age:20.height:177}]var filterPersons = persons.filter(function(person,index,arrs){
    return person.type === "boy";
})
console.log(filterPersons) // Filters the entire object of type boy and stuffs it into a new array

Copy the code

References (some mentioned above, in no particular order)

  1. “2021” high frequency front end test questions summary of JavaScript (part 1) “– CUGGZ
  2. “2021” high frequency front end test questions summary of JavaScript (part ii) “– CUGGZ
  3. Don’t rush me to code slowly
  4. “From the simple to the deep, 66 JavaScript interview knowledge points” by JakeZhang
  5. # 26 Selected JavaScript Interview Questions — Fundebug
  6. Further additions may follow

Finally:

Concept article I temporarily write here, these topics are I in this period of time to collect the current part of the company in advance batch, autumn recruitment of some front-end Js interview questions, in the future if encountered did not write the topic, I will continue to update here, if you find that I wrote a mistake, please be corrected, very grateful! Finally, I posted this period of reference to the article sources, thank you very much in the process of sorting out the big guys for my help, I also very harvest, thank you for reading O (^▽^)o, mutual encouragement.

– (finished)