Question 1 (60 front-end classic interview questions with answers)

Today, I share a comprehensive interview question, including JS, CSS, React, web, browser, program questions, etc.


(all answers below are for reference only)

Short answer

1. What is anti shake and throttling? What's the difference? How?

Reference answer

Anti shake

After triggering the high-frequency event, the function will be executed only once in n seconds. If the high-frequency event is triggered again in n seconds, the time will be recalculated

  • Idea:

Each time an event is triggered, the previous deferred call method is cancelled

  1. function debounce(fn) {
  2.       let timeout = null;  //  Create a tag to store the return value of the timer
  3.        return function () {
  4.         clearTimeout(timeout);  //  Whenever the user enters, the previous   setTimeout   clear   fall
  5.         timeout = setTimeout(() => {  //  Then create a new one   setTimeout,   In this way, you can ensure the accuracy after entering characters   interval   If there is still character input within the interval, it will not be executed   fn   function
  6.           fn.apply(this, arguments);
  7.         },  500);
  8.       };
  9.     }
  10.     function sayHi() {
  11.       console.log( 'Anti shake successful');
  12.     }
  13.      var inp = document.getElementById( 'inp');
  14.     inp.addEventListener( 'input', debounce(sayHi));  //  Anti shake


The high-frequency event is triggered, but it will only be executed once in n seconds, so throttling will dilute the execution frequency of the function

  • Idea:

Each time an event is triggered, judge whether there is a delay function waiting to be executed

  1. function throttle(fn) {
  2.       let canRun =  true;  //  Save a tag through a closure
  3.        return function () {
  4.          if (!canRun)  return;  //  Judge whether the flag is true at the beginning of the function. If it is not true, return
  5.         canRun =  false;  //  Set to false now
  6.         setTimeout(() => {  //  Put the execution of the externally passed in function in setTimeout
  7.           fn.apply(this, arguments);
  8.            //  Finally, after the setTimeout is executed, set the flag to true (key) to indicate that the next cycle can be executed. When the timer is not executed, the flag is always false and is return ed at the beginning
  9.           canRun =  true;
  10.         },  500);
  11.       };
  12.     }
  13.     function sayHi(e) {
  14.       console.log(,;
  15.     }
  16.     window.addEventListener( 'resize', throttle(sayHi));

2. The misunderstanding of parameter length of get request and the difference between get and post request in cache

Myth: we often say that the size of get request parameters is limited, while the size of post request parameters is unlimited.

Reference answer

In fact, the HTTP protocol never specifies the request length limit for GET/POST. The restriction on get request parameters is that the source is the browser or web server, which limits the length of the url. In order to clarify this concept, we must emphasize the following points again:

  • The HTTP protocol does not specify the length limit of GET and POST

  • The maximum length of GET is displayed because browsers and web servers limit the length of URI s

  • Different browsers and WEB servers have different maximum lengths

  • To support IE, the maximum length is 2083byte s. If only Chrome is supported, the maximum length is 8182byte s

Add the difference between get and post in caching:

  • The get request is similar to the search process. The user can obtain data without connecting to the database every time, so the cache can be used.

  • Unlike post, post usually does modification and deletion, so it must interact with the database, so it cannot use cache. Therefore, get requests are suitable for request caching.

3. Modular development process

From IIFE, AMD, CMD, CommonJS, UMD, webpack(require.ensure), ES Module, < script type = "module" >   From these angles.

Reference answer

Modularity is mainly used to extract public code, isolate scope, avoid variable conflict, etc.

IIFE: use self executing functions to write modularization. Features: execute code in a separate function scope to avoid variable conflict.

  1. (function(){
  2.    return {
  3.     data:[]
  4.   }
  5. })()

AMD: use requireJS to write modularization. Feature: dependencies must be declared in advance.

  1. define( './index.js',function(code){
  2.      //  code   index.js   Returned content
  3. })

CMD: use seaJS to write modularization. Feature: support the dynamic introduction of dependency files.

  1. define(function(require, exports, module) {  
  2.    var indexCode = require( './index.js');
  3. })

CommonJS: the built-in modularity in nodejs.

var fs = require('fs');


UMD: compatible with AMD and CommonJS modular syntax.

webpack(require.ensure): Code segmentation in webpack version 2. X.

ES Modules: the modularity introduced by ES6 supports import to introduce another js.

import a from 'a';


4. npm module installation mechanism. Why can the corresponding module be installed automatically by entering npm install?

Reference answer

1. npm module installation mechanism:

  • Issue the npm install command

  • Query node_ Whether the specified module already exists in the modules directory

    • npm queries the registry for the URL of the module's compressed package

    • Download the compressed package and store it in the. npm directory under the root directory

    • Unzip the compressed package to the node of the current project_ Modules directory

    • If present, do not reinstall

    • If not

2. npm implementation principle

After entering the npm install command and pressing enter, you will go through the following stages (take npm 5.5.1 as an example):

  1. Execute preinstall of the project itself

    If the preinstall hook is defined for the current npm project, it will be executed at this time.

  2. Determine the first layer dependent modules

    The first thing to do is to determine the first layer dependencies in the project, that is, the modules directly specified in the dependencies and devdependences attributes (assuming that the npm install parameter is not added at this time).

    The project itself is the root node of the whole dependency tree. Each first layer dependency module is a subtree under the root node. npm will start multiple processes to gradually find deeper nodes from each first layer dependency module.

  3. Acquisition module

    Module acquisition is a recursive process, which is divided into the following steps:

  • Get module information. Before downloading a module, you must first determine its version, because package.json is often a semantic Version (semver, semantic version). At this time, if the module information is available in the version description file (npm-shrinkwrap.json or package-lock.json), you can get it directly. If not, you can get it from the warehouse. If the version of a package in packageg.json is ^ 1.1.0, NPM will go to the warehouse to obtain the latest version in the form of 1.x.x.

  • Gets the module entity. In the previous step, the module's compressed packet address (resolved field) will be obtained. npm will use this address to check the local cache. If there is any in the cache, it will be taken directly. If not, it will be downloaded from the warehouse.

  • Find the module dependency. If there is a dependency, go back to step 1. If there is no dependency, stop.

  • Modular flattening

    What you got in the previous step is A complete dependency tree, which may contain A large number of duplicate modules. For example, module A depends on loadsh, and module B also depends on lodash. Before npm3, it will be installed in strict accordance with the dependency tree structure, which will cause module redundancy.

    Starting from npm3, a dedupe process is added by default. It will traverse all nodes and place modules one by one under the root node, that is, the first layer of node modules. When duplicate modules are found, they are discarded.

    Here, you need to define a duplicate module, which means that the module names are the same and   Semver compatible. Each semver corresponds to a version allowable range. If there is an intersection between the version allowable ranges of the two modules, you can get a compatible version without having to have the same version number, which can remove more redundant modules in the process of dedupe.

    For example, the foo module under node modules depends on lodash@^1.0.0, and the bar module depends on lodash@^1.1.0  ^ 1.1.0   Is a compatible version.

    When foo depends on lodash@^2.0.0 and bar depends on lodash@^1.1.0, there is no compatible version between them according to the rules of semver. A version will be placed on the node_ In modules, the other one remains in the dependency tree.

    For example, suppose a dependency tree is originally like this:

    -- foo
    ---- lodash@version1

    -- bar
    ---- lodash@version2

    Assuming that version1 and version2 are compatible versions, they will become the following form after dedupe:

    -- foo

    -- bar

    --lodash (the reserved version is a compatible version)

    Assuming that version1 and version2 are incompatible versions, the following versions remain in the dependency tree:

    -- foo
    -- lodash@version1

    -- bar
    ---- lodash@version2

  • Installation module

    This step will update the node in the project_ Modules and execute the life cycle functions in the module (in the order of preinstall, install and postinstall).

  • Perform the project's own life cycle

    If hooks are defined in the current npm project, they will be executed (in the order of install, postinstall, publish and prepare).

    The last step is to generate or update the version description file, and the npm install process is completed.

  • 5. What is the difference between ES5 inheritance and ES6 inheritance?

    Reference answer

    The inheritance of ES5 is implemented through the prototype or constructor mechanism. The essence of inheritance in ES5 is to create the instance object of the subclass first, and then add the method of the parent class to this (Parent.apply(this)).

    The inheritance mechanism of ES6 is completely different. In essence, the instance object this of the parent class is created first (so the super() method of the parent class must be called first), and then the constructor of the child class is used to modify this.

    Specifically: ES6 defines classes through the class keyword, which has construction methods. Classes inherit through the extends keyword. The subclass must call the super method in the constructor method, otherwise the new instance will be wrong. Because the subclass does not have its own this object, but inherits the this object of the parent class and processes it. If the super method is not called, the subclass cannot get the this object.

    ps: Super keyword refers to the instance of the parent class, that is, the this object of the parent class. In the subclass constructor, you can use the this keyword after calling super, otherwise you will report it wrong.

    6. Differences among setTimeout, Promise and async / wait

    Reference answer:

    7. The execution sequence or mechanism of the timer?

    Reference answer

    Because js is single threaded, when the browser encounters setTimeout or setInterval, it will first execute the current code block. Before that, it will push the timer into the browser's to be executed event queue. After the browser executes the current code, it will check whether there are tasks in the event queue. If so, it will execute the timer code. Therefore, even if the timer time is set to 0, some current code will be executed first.

    1. function test(){
    2.      var aa =  0;
    3.      var testSet = setInterval(function(){
    4.         aa++;
    5.         console.log( 123);
    6.          if(aa< 10){
    7.             clearInterval(testSet);
    8.         }
    9.     }, 20);
    10.    var testSet1 = setTimeout(function(){
    11.     console.log( 321)
    12.   }, 1000);
    13.    for( var i= 0;i< 10;i++){
    14.     console.log( 'test');
    15.   }
    16. }
    17. test()

    Output results:

    1. test  //10 times
    2. undefined
    3. 123
    4. 321

    8. What does ['1','2','3'].map(parseInt) output and why?

    Reference answer

    Output: [1, NaN, NaN]

    • First, let's review the first parameter callback of the map function:

    var new_array = callback(currentValue[, index[, array]]) { // Return element for new_array }[, thisArg])
    This callback can receive a total of three parameters, of which the first parameter represents the currently processed element and the second parameter represents the index of the element.

    • parseInt is used to parse the string and make the string an integer with a specified cardinality.
      parseInt(string, radix)
      Two parameters are received. The first represents the processed value (string) and the second represents the cardinality at the time of parsing.

    • After understanding these two functions, we can simulate the operation

    1. When parseInt ('1 ', 0) / / radius is 0 and the string parameter does not start with "0x" and "0", it is processed based on 10. This time returns 1

    2. parseInt('2', 1) / / among the numbers represented by Radix 1 (hexadecimal), the maximum value is less than 2, so it cannot be parsed. NaN is returned

    3. parseInt('3', 2) / / among the numbers represented by Radix 2 (binary), the maximum value is less than 3, so it cannot be parsed. NaN is returned

    • The map function returns an array, so the final result is [1, NaN, NaN]

    9. What is the role of Doctype? How to distinguish between strict mode and hybrid mode? What do they mean?

    Reference answer

    Doctype is declared at the front of the document to tell the browser how to render the page. There are two modes, strict mode and hybrid mode.

    • Strict mode typesetting and JS operation mode run according to the highest standard supported by the browser.

    • Hybrid mode, backward compatibility, simulate old browsers, and prevent browsers from being compatible with pages.

    10. The reason why the fetch sent the request twice

    Reference answer

    When a fetch sends a post request, it always sends it twice. The first time the status code is 204, and the second time it succeeds?

    The reason is very simple, because when you use the post request of the fetch, the fetch sends an Options request for the first time, asking whether the server supports the modified request header. If the server supports it, the real request will be sent in the second time.

    http, browser object

    1. How does the client verify the validity of the certificate during HTTPS handshake

    Reference answer

    • First, what is the HTTP protocol?

      http protocol is a hypertext transport protocol, which is located in the application layer of tcp/ip four layer model; Communicating between the client and the server through request / response; However, it lacks security. The information transmission of http protocol is transmitted in clear text without any encryption, which is equivalent to running naked on the network; It is easy to be maliciously tampered with by middlemen, which is called middleman attack;

    • Encrypted communication:

      For security, both parties can use symmetric encryption key to exchange information, but this symmetric encryption key will also be intercepted, which is not safe enough, and there is still a risk of being attacked by intermediaries;
      So people came up with another way, using asymmetric encryption; Encryption and decryption using public / private key; The communicating party a initiates the communication and carries its own public key, and the receiving Party B encrypts the symmetric secret key through the public key; Then send it to initiator a; A decrypts through the private key; The two transmitters then carry out encrypted communication through a symmetric secret key; However, there will still be a kind of security in this way; Although the middleman does not know the private key of initiator a, he can steal heaven and earth and intercept the initiator's public key; And send the public key of a pair of public / private keys generated by itself to B; Receiver B does not know that the public key has been changed secretly; According to the previous process, B encrypts the symmetric encryption key key2 generated by itself through the public key; Send to a;
      This communication was intercepted by the middleman again. Although the latter communication still uses Key2, the middleman has mastered Key2; Easy encryption and decryption; There is still a risk of being attacked by intermediaries;

    • Solve the dilemma: the authoritative certification authority CA to solve it;

      • Making A certificate: as A server, A first sends its public key key1 to the certification authority and applies for A certificate from the certification authority; The certification authority has its own set of public and private keys. CA encrypts key1 through its own private key, and generates A certificate signature through the server website and other information. The certificate signature is also encrypted by the authority's private key; After the production, the organization will issue the certificate to A;

      • Verify the authenticity of the certificate: when B sends A request communication to server A, A will no longer directly return its public key, but A certificate;

    Note: all major browsers and operating systems have maintained the names and public keys of all authoritative certification authorities. B only needs to know which authority issued the certificate and use the corresponding public key to decrypt the certificate signature; Next, B uses the same rules to generate its own certificate signature. If the two signatures are consistent, it indicates that the certificate is valid;
    After the signature verification is successful, B can decrypt A's public key key1 by using the organization's public key again; The next operation is the same process as before;

    • Will the middleman intercept sending fake certificates to B?

    Because the signature of the certificate is generated by the server-side Web address and other information, and is encrypted by the private key of a third-party institution, the middleman cannot tamper with it; Therefore, the key problem is the authenticity of the certificate signature;

    • The main idea of https is to add ssl security layer on the basis of http, that is, the above authentication process;

    2. TCP three handshakes and four waves

    Reference answer

    The reason why three handshakes are three is to ensure that both client and server let each other know that their receiving and sending capabilities are OK.

    For the first time, the client = > server can only judge that the client has the sending ability
    The second time server = > client, the client can judge that the server has the ability to send and receive. At this time, the client needs to let the server know that its receiving capacity is OK, so there is a third time
    The third time, both client = > server ensure that their receiving and sending capabilities are free from problems

    Among them, in order to ensure that the subsequent handshake is to answer the previous handshake, each handshake will carry an identification seq, and the subsequent ACK will add one to confirm this seq.

    3. What are the advantages and disadvantages of img iframe script to send cross domain requests?

    Reference answer

    • iframe

    Advantages: after the cross domain is completed, there is no problem with DOM operation and JavaScript calls between each other

    Disadvantages: 1. If the result is to be delivered with URL parameters, it means that it needs to be delivered separately when the amount of result data is large, which is very annoying. 2. 2. Another is brought by iframe itself. The interaction between the parent page and iframe itself has security restrictions.

    • script

    Advantages: it can directly return data in json format, which is convenient for processing

    Disadvantages: only GET requests are accepted

    • Picture ping

    Advantages: you can access any url, which is generally used for click tracking and page analysis

    Disadvantages: you cannot access the response text. You can only listen for the response

    4. What is the difference between http and https?

    Reference answer

    The data transmitted by http is unencrypted, that is, in clear text. Netscape has set up SSL protocol to encrypt the data transmitted by http protocol. In short, https protocol is a network protocol constructed by http and SSL protocol for encrypted transmission and identity authentication, which has higher security than http protocol. The main differences are as follows:

    • HTTP protocol requires ca certificate, and the cost is high.

    • http is a hypertext transmission protocol, information is plaintext transmission, and https is a secure ssl encrypted transmission protocol.

    • The ports are different with different linking methods. Generally speaking, the port of http protocol is 80 and the port of https is 443

    • http connection is simple and stateless; HTTPS protocol is a network protocol constructed by SSL+HTTP protocol, which can carry out encrypted transmission and identity authentication. It is safer than http protocol.

    5. What is Bom? What are the common Bom attributes?

    Reference answer

    Bom is a browser object

    location object

    • location.href -- returns or sets the URL of the current document

    • -- returns the part of the query string in the URL. For example Return the contents after (?)? id=5&name=dreamdu

    • location.hash -- returns the content after the URL # and if not #, returns null -- returns the domain name part of the URL, such as

    • location.hostname -- returns the main domain name part of the URL, such as

    • location.pathname -- returns the part after the domain name of the URL. For example Return / XHTML/

    • location.port -- returns the port portion of the URL. For example Return to 8080

    • location.protocol -- returns the protocol part of the URL. For example Return the content in front of (/ /). Http:

    • location.assign -- sets the URL of the current document

    • location.replace() -- set the URL of the current document and remove the URL location.replace(url) from the address list of the history object;

    • location.reload() -- reload the current page

    history object

    • history.go() -- forward or backward the specified number of pages

    • history.go(num); history.back() -- back one page

    • history.forward() -- forward one page

    Navigator object

    • navigator.userAgent -- returns the string representation of the user agent header (that is, the string including browser version information, etc.)

    • Navigator.cookie enabled -- returns whether the browser supports (enables) cookies

    6. Differences among Cookie, sessionStorage and localStorage

    Reference answer

    Common ground: they are stored on the browser side and are homologous

    • Cookie: the cookie data is always carried in the http request of the same origin (even if it is not needed), that is, the cookie is passed back and forth between the browser and the server. sessionStorage and localStorage do not automatically send data to the server, but only save it locally. Cookie data also has the concept of path, which can limit the cookie to only belong to a certain path, and the storage size is very small, only about 4K. (key: it can be passed back and forth between the browser and the server. The storage capacity is small, only about 4K)

    • sessionStorage: it is valid only before the current browser window is closed, so it cannot be persisted. localStorage: it is always valid, and the window or browser is always saved when it is closed, so it is used as persistent data; Cookies are only valid until the set cookie expiration time, even if the window or browser is closed. (key: it is a reply process. It disappears after closing the browser. The session is a reply. When the pages are different, even if the same page is opened twice, it is regarded as the same reply.)

    • localStorage: localStorage is shared in all source windows; Cookies are also shared in all cognate windows. (key: windows of the same origin will be shared and will not become invalid. It will always take effect whether the window or browser is closed or not)

    The role of cookie s is supplemented:

    • Save user login status. For example, the user id is stored in a cookie, so that users do not need to log in again when they visit the page next time. Many forums and communities now provide this function. Cookies can also be set to expire. When the time limit is exceeded, the cookie will disappear automatically. Therefore, the system can often prompt the user to stay logged in: common options include one month, three months, one year, etc.

    • Track user behavior. For example, a weather forecast website can display the local weather according to the area selected by the user. If you need to select the location every time, it is cumbersome. It will be very humanized after using cookie s. The system can remember the last visited region. When you open the page next time, it will automatically display the weather of the last user's region. Because everything is done in the background, such a page is like customized for a user, which is very convenient to use

    • Customize the page. If the website provides the function of skin changing or layout changing, cookie s can be used to record the user's options, such as background color, resolution, etc. When the user visits the next time, the interface style of the last visit can still be saved.

    7. How cookies protect against XSS attacks

    Reference answer

    XSS (cross site scripting attack) means that the attacker embeds javascript scripts in the returned HTML. In order to mitigate these attacks, set cookies need to be added to the HTTP header:

    • httponly - this attribute prevents XSS, which prevents javascript scripts from accessing cookie s.

    • secure - this property tells the browser to send cookie s only when the request is https.

    The result should be: set cookie =

    8. What is the difference between browser and Node event loops?

    Reference answer

    One of the main differences is that the order of handling asynchronous events is different between the browser's event loop and nodejs' event loop. There are micro events in nodejs; Promise belongs to micro event, and the processing order of asynchronous events is different from that of the browser. The order between nodejs V11.0 and above is the same

    1. function test () {
    2.    console.log( 'start')
    3.     setTimeout(() => {
    4.         console.log( 'children2')
    5.         Promise.resolve().then(() => {console.log( 'children2-1')})
    6.     },  0)
    7.     setTimeout(() => {
    8.         console.log( 'children3')
    9.         Promise.resolve().then(() => {console.log( 'children3-1')})
    10.     },  0)
    11.     Promise.resolve().then(() => {console.log( 'children1')})
    12.     console.log( 'end') 
    13. }
    14. test()
    15. //  The execution results of the above code in versions below node11 (execute all macro tasks first, and then micro tasks)
    16. // start
    17. // end
    18. // children1
    19. // children2
    20. // children3
    21. // children2-1
    22. // children3-1
    23. //  Execution results of the above code in node11 and browser (macro task and micro task are executed in sequence)
    24. // start
    25. // end
    26. // children1
    27. // children2
    28. // children2-1
    29. // children3
    30. // children3-1

    9. Brief description of HTTPS man in the middle attack

    Reference answer

    https protocol is composed of http + ssl protocol. For the specific link process, please refer to the overview of SSL or TLS handshake

    The process of man in the middle attack is as follows:

    1. The server sends the public key to the client.

    2. The attacker intercepts the public key and keeps it in his hand.

    3. Then the attacker generates a [forged] public key and sends it to the client.

    4. After receiving the forged public key, the client generates an encrypted hash value and sends it to the server.

    5. The attacker obtains the encrypted hash value and decrypts it with his own private key to obtain the true secret key.

    6. At the same time, a false encrypted hash value is generated and sent to the server.

    7. The server decrypts the private key to obtain a false secret key.

    8. The server encrypts the transmission information with a secret key


    1. The server adds the CA certificate to the public key of the sending browser, and the browser can verify the validity of the CA certificate

    10. Some web front-end optimization strategies

    Reference answer

    (1) . reduce the number of HTTP requests

    This strategy is basically known to all front-end people, and it is also the most important and effective. It is said to reduce HTTP requests. What happens when there are more requests? First, each request has a cost, including both time cost and resource cost. A complete request needs a "long" and complex process of DNS addressing, establishing a connection with the server, sending data, waiting for the server response and receiving data. The time cost is that users need to see or "feel" this resource and have to wait for the end of this process. In terms of resources, each request needs to take up bandwidth because it needs to carry data.

    In addition, since there is an upper limit on the number of concurrent requests made by the browser, when the number of requests is large, the browser needs to make requests in batches, which will increase the waiting time of users and give users the impression that the site speed is slow. Even if the resources on the first screen that users can see have been requested, the progress bar of the browser will always exist. The main ways to reduce the number of HTTP requests include:

    (2) Simplify the page from the design and implementation level

    If your page is as simple as Baidu home page, then the next rules are basically unnecessary. It is the most direct way to keep the page concise and reduce the use of resources. If this is not the case and your page needs gorgeous skin, continue to read the following content.

    (3) . reasonably set HTTP cache

    The power of caching is powerful. Proper cache settings can greatly reduce HTTP requests. Take YOUAH homepage as an example. When the browser is not cached, a total of 78 requests will be sent for access, with a total of more than 600 k data (as shown in Figure 1.1), while when the browser is cached for the second access, there are only 10 requests, with a total of more than 20 K data (as shown in Figure 1.2). (it should be noted here that if you refresh the page directly with F5, the effect is different. In this case, the number of requests is the same, but the request server of cached resources responds with 304. Only the Header has no Body, which can save bandwidth.)

    What is the reasonable setting? The principle is very simple. The more you can cache, the better. The longer you can cache, the better. For example, for rarely changed picture resources, you can directly set a long expiration header through Expires in the HTTP Header; For resources that change infrequently and may change, last modified can be used for request verification. Make resources stay in the cache longer as possible.

    (4) . resource consolidation and compression

    If possible, merge external scripts and styles as much as possible, and combine multiple into one. In addition, CSS, Javascript and Image can be compressed with corresponding tools, which often saves a lot of space after compression.

    (5). CSS Sprites

    Merging CSS images is another good way to reduce the number of requests.

    (6). Inline Images

    Using data: URL scheme to embed images into pages or CSS is a good way if resource management problems are not considered. If the page is embedded, it will increase the volume of the page and cannot use the browser cache. Images used in CSS are more ideal.

    (7). Lazy Load Images

    This strategy does not necessarily reduce the number of HTTP requests, but it can reduce the number of HTTP requests under certain conditions or when the page is just loaded. For pictures, only the first screen can be loaded when the page is just loaded, and subsequent pictures can be loaded only when the user continues to scroll back. In this way, if the user is only interested in the content of the first screen, the remaining picture requests are saved. Yes, the home page used to cache the picture address after the first screen in the Textarea tag when loading, and only "inert" loading when the user scrolls down the screen.

    11. Do you understand the performance problems caused by redrawing and reflow of your browser

    Reference answer

    Repaint and Reflow

    Redraw and reflow are part of the rendering steps, but they have a significant impact on performance.

    • Redrawing is when a node needs to change its appearance without affecting the layout, such as changing   color is called redrawing

    • Reflow is when the layout or geometric properties need to be changed, it is called reflow.

    Reflow is bound to redraw, and redraw does not necessarily lead to reflow. The cost of backflow is much higher. Changing deep-seated nodes is likely to lead to a series of backflow of parent nodes.

    Therefore, the following actions may cause performance problems:

    • Change window size

    • Change font

    • Add or remove styles

    • Text change

    • Positioning or floating

    • Box model

    What many people don't know is that redrawing and reflow are actually related to Event loop.

    1. After Event loop executes Microtasks, it will judge whether the document needs to be updated. Because the browser has a refresh rate of 60Hz, it will be updated every 16ms.

    2. Then judge whether there is   resize or   Scroll, some events will be triggered, so   resize and   The scroll event is triggered at least once every 16ms, and has its own throttling function.

    3. Judge whether media query is triggered

    4. Update animation and send events

    5. Determine whether there are full screen operation events

    6. implement   requestAnimationFrame callback

    7. implement   InterpObserver callback. This method is used to determine whether the element is visible. It can be used for lazy loading, but the compatibility is not good

    8. Update interface

    9. That's what you might do in a frame. If there is free time in a frame, it will be executed   requestIdleCallback callback.

    Reduce redrawing and reflow

    • use   translate   replace   top

      1. <div class= "test"></div>
      2. <style>
      3.   .test {
      4.       position: absolute;
      5.       top:  10px;
      6.       width:  100px;
      7.       height:  100px;
      8.       background: red;
      9.   }
      10. </style>
      11. <script>
      12.   setTimeout(() => {
      13.        //  Cause backflow
      14.       document.querySelector( '.test') =  '100px'
      15.   },  1000)
      16. </script>
    • use   visibility replacement   display: none, because the former will only cause redrawing, and the latter will cause reflow (changing the layout)

      Take the DOM offline and modify it. For example, give the DOM to the user first   Display: none (reflow once), then you modify it 100 times, and then display it

      Don't put the attribute values of DOM nodes in a loop as variables in the loop

      1. for(let i =  0; i <  1000; i++) {
      2.    //  obtain   offsetTop   It will cause backflow because you need to get the correct value
      3.   console.log(document.querySelector( '.test').style.offsetTop)
      4. }
    • Do not use the table layout. A small change may cause the whole table to be rearranged

    • Choose the speed of animation. The faster the animation speed is, the more reflow times are. You can also choose to use it   requestAnimationFrame

    • CSS selectors match and search from right to left to avoid too deep DOM depth

    • Turn the frequently running animation into a layer, which can prevent the reflow of this node from affecting other elements. For example, for   video tag, the browser will automatically turn the node into a layer.


    1. Why should I write a key in the list component when writing a React / Vue project? What is its function?

    Reference answer

    vue and react both use diff algorithm to compare the old and new virtual nodes, so as to update the nodes. In the diff function of vue (it is recommended to understand the diff algorithm process first).
    In cross comparison, when there is no result of cross comparison between the new node and the old node, the key in the old node array will be compared according to the key of the new node, so as to find the corresponding old node (here corresponds to a map mapping of key = > index). If it is not found, it is considered as a new node. If there is no key, the corresponding old node will be found by traversal. One is a map map, the other is a traversal search. In contrast. Map mapping is faster.
    The source code of vue is as follows:

    1. //  vue project    src/core/vdom/patch.js   - Line 488
    2. //  The following is the formatted code for readability
    3. //  oldCh   Is an array of old virtual nodes
    4. if (isUndef(oldKeyToIdx)) {
    5.   oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
    6. }
    7. if(isDef(newStartVnode.key)) {
    8.    //  map   Method acquisition
    9.   idxInOld = oldKeyToIdx[newStartVnode.key]
    10. }  else {
    11.    //  Traversal acquisition
    12.   idxInOld = findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)
    13. }

    Create map function

    1. function createKeyToOldIdx (children, beginIdx, endIdx) {
    2.   let i, key
    3.    const  map = {}
    4.    for (i = beginIdx; i <= endIdx; ++i) {
    5.     key = children[i].key
    6.      if (isDef(key))  map[key] = i
    7.   }
    8.    return  map
    9. }

    Traversal search

    1. //  sameVnode   It is a function to compare whether the old and new nodes are the same
    2.  function findIdxInOld (node, oldCh, start, end) {
    3.      for (let i = start; i < end; i++) {
    4.        const c = oldCh[i]
    6.        if (isDef(c) && sameVnode(node, c))  return i
    7.     }
    8.   }

    2. When is setState synchronous and asynchronous in React?

    Reference answer

    In React, if it is an event processing triggered by React (such as an event processing triggered by onClick), calling setState will not update this.state synchronously, and other setState calls will execute this.state synchronously. The so-called "in addition" refers to the event handling functions directly added through addEventListener to bypass React, as well as the asynchronous calls generated through setTimeout/setInterval.

    **Reason: * * in the implementation of the setState function of React, whether to update this.state directly or put it in the queue will be determined according to a variable isBatchingUpdates. I'll talk about it later. isBatchingUpdates is false by default, which means that setState will update this.state synchronously. However, there is a function batchedUpdates, which will modify isBatchingUpdates to true, When React calls the batchedUpdates before calling the event handling function, the consequence is that the event handling process setState controlled by React will not update this.state synchronously.

    3. What is output below

    1. class Example extends React.Component {
    2.   constructor() {
    3.     super();
    4.     this.state = {
    5.       val:  0
    6.     };
    7.   }
    9.   componentDidMount() {
    10.     this.setState({val: this.state.val +  1});
    11.     console.log(this.state.val);     //  The first   one   second   log
    12.     this.setState({val: this.state.val +  1});
    13.     console.log(this.state.val);     //  The first   two   second   log
    14.     setTimeout(() => {
    15.       this.setState({val: this.state.val +  1});
    16.       console.log(this.state.val);   //  The first   three   second   log
    17.       this.setState({val: this.state.val +  1});
    18.       console.log(this.state.val);   //  The first   four   second   log
    19.     },  0);
    20.   }
    21.   render() {
    22.      return null;
    23.   }
    24. };
    1. 1,The first and second were in react In its own life cycle, when triggered isBatchingUpdates by  true,Therefore, updates are not performed directly state,But joined dirtyComponents,Therefore, the status before update is obtained during printing  0.
    2. 2,twice setState When, get this.state.val All  0,So the execution is  0 Set as 1,stay react The internal will be merged and executed only once. After setting state.val Value is 1.
    3. 3,setTimeout Code in, when triggered isBatchingUpdates by  false,So it can be updated directly, so it is connected with output 2, 3.
    4. Output:  0  0 2 3

    4. Why does virtual dom improve performance?

    Reference answer

    Virtual DOM is equivalent to adding a cache between js and real dom. dom diff algorithm is used to avoid unnecessary DOM operations, so as to improve performance.

    The specific implementation steps are as follows:

    The structure of DOM tree is represented by JavaScript object structure; Then use this tree to build a real DOM tree and insert it into the document

    When the state changes, reconstruct a new object tree. Then compare the new tree with the old tree and record the difference between the two trees

    Apply the differences recorded in step 2 to the real DOM tree built in step 1, and the view is updated.


    1. Analyze and compare the advantages and disadvantages of opacity: 0, visibility: hidden, display: none and applicable scenarios

    Reference answer

    display:none: it will make the elements completely disappear from the rendering tree. When rendering, it does not occupy any space and cannot be clicked,
    visibility: hidden: elements will not disappear from the rendering tree. Rendering elements continue to occupy space, but the content is invisible and cannot be clicked
    opacity: 0: elements will not disappear from the rendering tree. Rendering elements continue to occupy space, but the content is invisible. You can click

    display: none and opacity: 0: it is a non inherited attribute. The descendant node disappears. Because the element disappears from the rendering tree, it cannot be displayed by modifying the descendant node attribute.
    visibility: hidden: it is an inherited attribute. The descendant node disappears. Because it inherits hidden, set visibility: visible; You can make descendant nodes explicit.

    displaynone: modifying the element will cause document reflow. The screen reader will not read the content of the display: none element, which consumes a lot of performance
    visibility:hidden: modifying an element will only cause redrawing of the element, with less performance consumption. The screen reader reads the content of the visibility:hidden element
    opacity: 0: modifying elements will cause redrawing and consume less performance

    Connection: they all make elements invisible

    2. What are the ways to clear floats? Which one is better?

    Reference answer

    Three types of. clearfix are commonly used,   clear:both,overflow:hidden;

    Better yes  . clearfix, pseudo element panacea version, the latter two have limitations

    1. .clearfix:after {
    2.   visibility: hidden;
    3.   display: block;
    4.   font-size:  0;
    5.   content:  " ";
    6.   clear: both;
    7.   height:  0;
    8. }
    9. <!--
    10. Why not zoom ,_height these,IE6, 7 Such needs csshack We don't think about it anymore
    11. .clearfix There is another way to write,
    12. -->
    13. .clearfix:before, .clearfix:after {
    14.     content: "";
    15.     display:table;
    16. }
    17. .clearfix:after{
    18.     clear:both;
    19.     overflow:hidden;
    20. }
    21. .clearfix{
    22.     zoom: 1;
    23. }
    24. <!--
    25. use display:table To avoid outer margins margin Caused by overlap margin Collapse,
    26. Internal elements become by default table-cell Form of cell
    27. -->

    clear:both: if it is used on adjacent elements in the same container, it is good. Sometimes there are some problems outside the container, such as the collapse of wrapping elements in adjacent containers

    overflow:hidden: this can be formed if it is used in the same container   BFC avoids element collapse caused by floating

    4. What is css sprite and what are its advantages and disadvantages

    Reference answer

    Concept: splice multiple small pictures into one picture. Adjust the background pattern to be displayed through background position and element size.


    1. Reduce the number of HTTP requests and greatly improve the page loading speed

    2. Increase the picture information repeatability, improve the compression ratio and reduce the picture size

    3. It is convenient to change the style. You only need to modify the color or style on one or several pictures


    1. Picture merging trouble

    2. Maintenance is troublesome. Modifying a picture may need to rearrange the whole picture and style

    5. The difference between link and @ import

    Reference answer

    1. link is HTML,  @ import is CSS mode

    2. link supports parallel downloading to the maximum extent. Too much nesting of @ import leads to serial downloading and FOUC

    3. link you can specify candidate styles through rel="alternate stylesheet"

    4. The browser supports link earlier than @ import. You can use @ import to hide the style from the old browser

    5. @import must precede the style rule, and other files can be referenced in the css file

    6. Overall: link is better than @ import

    6,display: block; And display: inline; Differences between

    Reference answer

    block element features:

    1. When in the regular flow, if the width is not set, the parent container will be filled automatically. 2. margin/padding can be applied   3. If the height is not set, the height will be expanded to include the child elements in the regular flow. 4. When in the regular flow, the layout will be between the front and rear element positions (exclusive of a horizontal space) 5. Ignore vertical align

    inline element features

    1. Layout in order according to the direction in the horizontal direction

    2. Do not wrap around elements

    3. Controlled by white space

    4.margin/padding is invalid in the vertical direction and valid in the horizontal direction

    5. The width / height attribute is invalid for elements in non replacement lines. The width is determined by the element content

    6. The row box height of elements in non replacement rows is determined by line height, and the row box height of elements in replacement rows is determined by height, margin, padding and border
    7. It will be converted to block when floating or absolute positioning
    8. Vertical align attribute takes effect

    7. How to clean up floating when a container contains several floating elements

    Reference answer

    1. Add additional elements and set before the container element closes the label`clear: both`
    2. The parent element triggers a block level formatting context\(See the block level visualization context section\)
    3. Set container element pseudo element for cleanup
    1. /**
    2. * Use in standard browser
    3. * 1 content The content is blank, which is used to fix the problem in the document under opera
    4. *   contenteditable Property to clean up the white space above and below the floating element
    5. * 2 Use display, use table instead of block: you can prevent containers and
    6. *   The sub element top margin is folded, which can make the cleaning effect consistent with BFC and IE6/7
    7. *   zoom: 1;agreement
    8. **/
    9. .clearfix:before,
    10. .clearfix:after {
    11.     content:  " ";  /* 1 */
    12.     display: table;  /* 2 */
    13. }
    14. .clearfix:after {
    15.     clear: both;
    16. }
    17. /**
    18. * IE 6/7 Use under
    19. * Include floats by triggering hasLayout
    20. **/
    21. .clearfix {
    22.     *zoom:  1;
    23. }

    8. Differences between PNG, GIF and JPG and how to select them

    Reference answer


    1. 8-bit pixels, 256 colors

    2. lossless compression

    3. Support simple animation

    4. Support boolean transparency

    5. Suitable for simple animation


    1. Color limited to 256

    2. Lossy compression

    3. Controllable compression quality

    4. Transparency is not supported

    5. Suitable for photos


    1. There are PNG8 and truecolor PNG

    2. PNG8 is similar to GIF. The upper color limit is 256. The file is small. It supports alpha transparency and has no animation

    3. Suitable for icons, backgrounds, buttons

    9. Relationship between display, float and position

    Reference answer

    1. If display is none, neither position nor float will work. In this case, the element will not generate a box

    2. Otherwise, if the position value is absolute or fixed, the box is absolutely positioned, the calculated value of float is none, and display is adjusted according to the following table.

    3. Otherwise, if the float is not none, the box is floating, and the display is adjusted according to the following table

    4. Otherwise, if the element is the root element, display adjusts according to the following table

    5. In other cases, the value of display is the specified value. To sum up, the display needs to be adjusted for absolute positioning, floating and root elements

    10. How to center an element horizontally

    Reference answer

    • If the element to be centered is the inline element in the regular flow, set text align: Center for the parent element; Can be achieved

    • If the element to be centered is the block element in the regular flow, 1) set the width for the element, and 2) set the left and right margin to auto. 3) Under IE6, you need to set text align: Center; on the parent element;, Then restore the required values to the child elements

      1. <body>
      2.   <div class= "content">
      3.   aaaaaa aaaaaa a a a a a a a a
      4.   </div>
      5. </body>
      6. <style>
      7.   body {
      8.       background: #DDD;
      9.       text-align: center;  /* 3 */
      10.   }
      11.   .content {
      12.       width:  500px;       /* 1 */
      13.       text-align: left;   /* 3 */
      14.       margin:  0 auto;     /* 2 */
      15.       background: purple;
      16.   }
      17. </style>
    • If the element to be centered is a floating element, 1) set the width for the element, 2) position: relative;, 3) The floating direction offset (left or right) is set to 50%, and 4) the margin in the floating direction is set to half the element width multiplied by - 1

      1. <body>
      2.   <div class= "content">
      3.   aaaaaa aaaaaa a a a a a a a a
      4.   </div>
      5. </body>
      6. <style>
      7.   body {
      8.       background: #DDD;
      9.   }
      10.   .content {
      11.       width:  500px;          /* 1 */
      12.       float: left;
      13.       position: relative;    /* 2 */
      14.       left:  50%;             /* 3 */
      15.       margin-left:  -250px;   /* 4 */
      16.       background-color: purple;
      17.   }
      18. </style>
    • If the element to be centered is an absolute positioning element, 1) set the width for the element, 2) set the offset to 50%, and 3) set the outer margin in the offset direction to half the element width multiplied by - 1

      1. <body>
      2.   <div class= "content">
      3.   aaaaaa aaaaaa a a a a a a a a
      4.   </div>
      5. </body>
      6. <style>
      7.   body {
      8.       background: #DDD;
      9.       position: relative;
      10.   }
      11.   .content {
      12.       width:  800px;
      13.       position: absolute;
      14.       left:  50%;
      15.       margin-left:  -400px;
      16.       background-color: purple;
      17.   }
      18. </style>
    • If the element to be centered is an absolute positioning element, 1) set the width for the element, 2) set the left and right offsets to 0, and 3) set the left and right outer margins to auto

      1. <body>
      2.   <div class= "content">
      3.   aaaaaa aaaaaa a a a a a a a a
      4.   </div>
      5. </body>
      6. <style>
      7.   body {
      8.       background: #DDD;
      9.       position: relative;
      10.   }
      11.   .content {
      12.       width:  800px;
      13.       position: absolute;
      14.       margin:  0 auto;
      15.       left:  0;
      16.       right:  0;
      17.       background-color: purple;
      18.   }
      19. </style>


    1. JS has several data types, among which are the basic data types?

    Reference answer

    Seven data types

    • Boolean

    • Null

    • Undefined

    • Number

    • String

    • Symbol (ECMAScript 6 new definition)

    • Object

    (before ES6) five of them are basic types: string,number,boolean,null,undefined,

    The Symbol from ES6 is also the original data type and represents a unique value

    Object is a reference type (with a large range), including arrays and functions,

    2. Whether the Promise constructor is executed synchronously or asynchronously, what about the then method?

    Reference answer

    1. const promise =  new Promise((resolve, reject) => {
    2.   console.log( 1)
    3.   resolve()
    4.   console.log( 2)
    5. })
    6. promise.then(() => {
    7.   console.log( 3)
    8. })
    9. console.log( 4)

    The output is:

    1. 1
    2. 2
    3. 4
    4. 3
    5. promise Constructors are executed synchronously, then Methods are executed asynchronously
    6. Promise  new The code inside will be executed immediately then It's a micro task It will be executed at the end of this task setTimeout Is a macro task It will be executed when the next task is executed

    3. Four design patterns of JS

    Reference answer

    Factory mode

    A simple factory model can be understood as solving multiple similar problems;

    1. function CreatePerson(name,age,sex) {
    2.      var obj =  new Object();
    3. = name;
    4.     obj.age = age;
    5. = sex;
    6.     obj.sayName = function(){
    7.          return;
    8.     }
    9.      return obj;
    10. }
    11. var p1 =  new CreatePerson( "longen", '28', 'male');
    12. var p2 =  new CreatePerson( "tugenhua", '27', 'female');
    13. console.log(;  // longen
    14. console.log(p1.age);   // 28
    15. console.log(;   //  male
    16. console.log(p1.sayName());  // longen
    17. console.log(;   // tugenhua
    18. console.log(p2.age);    // 27
    19. console.log(;    //  female
    20. console.log(p2.sayName());  // tugenhua  

    Singleton mode

    It can only be instantiated once (the constructor adds properties and methods to the instance)

    1. //  Monomer mode
    2. var Singleton = function(name){
    3. = name;
    4. };
    5. Singleton.prototype.getName = function(){
    6.      return;
    7. }
    8. //  Get instance object
    9. var getInstance = (function() {
    10.      var instance = null;
    11.      return function(name) {
    12.          if(!instance) { //It is equivalent to a disposable valve and can only be instantiated once
    13.             instance =  new Singleton(name);
    14.         }
    15.          return instance;
    16.     }
    17. })();
    18. //  Test the instance of monomer mode, so a =
    19. var a = getInstance( "aa");
    20. var b = getInstance( "bb");  

    Sandbox mode

    Put some functions into self executing functions, but expose the interface with closures, receive the exposed interface with variables, and then call the values inside, otherwise the values inside cannot be used

    1. let sandboxModel=(function(){
    2.     function sayName(){};
    3.     function sayAge(){};
    4.      return{
    5.         sayName:sayName,
    6.         sayAge:sayAge
    7.     }
    8. })()

    Publisher subscription mode

    For example, if we are concerned about a official account, then he will send you a new message.

    1. //Publisher and subscription mode
    2.      var shoeObj = {};  //  Define publisher
    3.     shoeObj.list = [];  //  Cache list   Store subscriber callback function
    4.      //  Add subscriber
    5.     shoeObj.listen = function(fn) {
    6.         shoeObj.list.push(fn);  //  Add subscription message to cache list
    7.     }
    8.      //  Release news
    9.     shoeObj.trigger = function() {
    10.              for ( var i =  0, fn; fn = this.list[i++];) {
    11.                 fn.apply(this, arguments); //The first parameter just changes this of fn,
    12.             }
    13.         }
    14.       //  Xiao Hong subscribes to the following message
    15.     shoeObj.listen(function(color, size) {
    16.         console.log( "The color is:" + color);
    17.         console.log( "Size:" + size);
    18.     });
    19.      //  Xiaohua subscribes to the following message
    20.     shoeObj.listen(function(color, size) {
    21.         console.log( "The color to print again is:" + color);
    22.         console.log( "Print the size again:" + size);
    23.     });
    24.     shoeObj.trigger( "gules",  40);
    25.     shoeObj.trigger( "black",  42);  

    The code implementation logic uses an array to store subscribers. The notification method in the publisher callback function is to traverse the subscriber array and pass the publisher content into the subscriber array

    4. List the methods of creating instances in a centralized way

    Reference answer

    1. Literal quantity

    let obj={'name':'Zhang San'}

    2.Object constructor creation

    1. let Obj= new Object()
    2. 'Zhang San'

    3. Create objects using factory mode

    1. function createPerson(name){
    2.   var o =  new Object();
    3. = name;
    4.  };
    5.   return o; 
    6. }
    7. var person1 = createPerson( 'Zhang San');

    4. Create objects using constructors

    1. function Person(name){
    2. = name;
    3. }
    4. var person1 =  new Person( 'Zhang San');

    5. Briefly describe the front-end event flow

    Reference answer

    Interaction with javascript in HTML is realized through event driven, such as mouse click event onclick, page scrolling event onscroll, etc. event listeners can be added to documents or elements in documents to subscribe to events. To know when these events are called, you need to understand the concept of "event flow".

    What is event flow: event flow describes the order in which events are received from the page. DOM2 level event flow includes the following stages.

    • Event capture phase

    • At target stage

    • Event bubbling phase

    addEventListener: addEventListener is the operation of the specified event handler added by DOM2 level events. This method receives three parameters: the name of the event to be processed, the function as the event handler, and a Boolean value. Finally, if the Boolean parameter is true, it means that the event handler is called in the capture phase; If false, the event handler is called during the bubbling phase.

    IE only supports event bubbling.

    6,Function._ proto_ What is (getprototypeof)?

    Reference answer

    Get the prototype of an object, which can be used in chrome__ proto__ Or in ES6, you can use the form of Object.getPrototypeOf.

    So what is Function.proto? That is to say, the object from which the Function is inherited, let's make the following judgment.

    1. Function.__proto__==Object.prototype  //false
    2. Function.__proto__==Function.prototype //true

    We found that the prototype of Function is also Function.

    We can clarify this relationship with a diagram:


    7. Briefly describe the prototype / constructor / instance

    Reference answer

    • Prototype: a simple object used to implement the   Property inheritance. It can be simply understood as the father of the object. In Firefox and Chrome, each JavaScript object contains a__ proto__ The (non-standard) attribute points to its parent (the prototype of the object), which can be obj__ proto__ Visit.

    • Constructor: you can use new to   Create a new object function.

    • Instance: the object created by constructor and new is an instance. Instance pass__ proto__ Point to the prototype, and point to the constructor through the constructor.

    Here's a chestnut. Take Object as an example. Our commonly used Object is a constructor, so we can build instances through it.

    1. //  example
    2. const instance =  new Object()

    Then at this time,   The instance is instance,   The constructor is Object. We know that the constructor has a prototype attribute pointing to the prototype, so the prototype is:

    1. //  prototype
    2. const prototype = Object.prototype

    Here we can see the relationship between the three:

    1. example.__proto__ === prototype
    2. prototype.constructor === Constructor
    3. Constructor.prototype === prototype
    4. //  This line is actually obtained based on the prototype, which can be understood as a reflection ray based on the prototype
    5. //  For example:  
    6. // const o = new Object()
    7. // o.constructor === Object   --> true
    8. // o.__proto__ = null;
    9. // o.constructor === Object   --> false
    10. example.constructor === Constructor

    8. Briefly describe JS inheritance and give examples

    Reference answer

    In JS, inheritance usually refers to   Prototype chain inheritance, that is, by specifying the prototype, and you can inherit the properties or methods on the prototype through the prototype chain.

    • Optimization:   Grail mode

      1. var inherit = (function(c,p){
      2.    var F = function(){};
      3.    return function(c,p){
      4.       F.prototype = p.prototype;
      5.       c.prototype =  new F();
      6.       c.uber = p.prototype;
      7.       c.prototype.constructor = c;
      8.   }
      9. })();
    • Syntax sugar using ES6   class / extends

    9. Function coritization

    Reference answer

    In functional programming, functions are first-class citizens. So what is the function coriolism?

    Function corrilization refers to the technology of converting a function that can receive multiple parameters into a function that receives a single parameter and returns a new function that receives the remaining parameters and returns the result.

    The main functions and characteristics of function coritization are parameter reuse, early return and delayed execution.

    In a function, the technique of first filling in several parameters and then returning a new function is called function coritization. It can usually be used to create a function without invading the function   Preset general parameters for repeated calls.

    1. const add = function add(x) {
    2.      return function (y) {
    3.          return x + y
    4.     }
    5. }
    6. const add1 = add( 1)
    7. add1( 2) ===  3
    8. add1( 20) ===  21

    10. Tell me the difference between bind, call and apply?

    Reference answer

    call   and   apply   It's all about change   this   The direction of. The functions are the same, but the methods of parameter transmission are different.

    Except for the first parameter, call   You can receive a parameter list, apply   Only one parameter array is accepted.

    1. let a = {
    2.     value:  1
    3. }
    4. function getValue(name, age) {
    5.     console.log(name)
    6.     console.log(age)
    7.     console.log(this.value)
    8. }
    9.,  'yck',  '24')
    10. getValue.apply(a, [ 'yck',  '24'])

    bind has the same function as the other two methods, except that this method will return a function. And we can pass   bind to achieve curry.

    (the following is an extended introduction to these three methods)

    How to implement a bind function

    For the implementation of the following functions, we can think from several aspects

    • If the first parameter is not passed in, the default is   window

    • Changed the point of this so that the new object can execute the function. So can the idea be to add a function to a new object and delete it after execution?

    1. Function.prototype.myBind = function (context) {
    2.    if (typeof this !==  'function') {
    3.     throw  new TypeError( 'Error')
    4.   }
    5.    var _this = this
    6.    var args = [...arguments].slice( 1)
    7.    //  Returns a function
    8.    return function F() {
    9.      //  Because a function is returned, we can   new   F(), so it needs to be judged
    10.      if (this instanceof F) {
    11.        return  new _this(...args, ...arguments)
    12.     }
    13.      return _this.apply(context, args.concat(...arguments))
    14.   }
    15. }

    How to implement a call function

    1. Function.prototype.myCall = function (context) {
    2.    var context = context || window
    3.    //  to   context   Add a property
    4.    //, 'yck', '24') => a.fn = getValue
    5.   context.fn = this
    6.    //  take   context   Take out the following parameters
    7.    var args = [...arguments].slice( 1)
    8.    //, 'yck', '24') => a.fn('yck', '24')
    9.    var result = context.fn(...args)
    10.    //  delete   fn
    11.    delete context.fn
    12.    return result
    13. }

    How to implement an apply function

    1. Function.prototype.myApply = function (context) {
    2.    var context = context || window
    3.   context.fn = this
    4.    var result
    5.    //  You need to determine whether to store the second parameter
    6.    //  If so, expand the second parameter
    7.    if (arguments[ 1]) {
    8.     result = context.fn(...arguments[ 1])
    9.   }  else {
    10.     result = context.fn()
    11.   }
    12.    delete context.fn
    13.    return result
    14. }

    11. Characteristics of arrow function

    Reference answer

    1. function a() {
    2.      return () => {
    3.          return () => {
    4.             console.log(this)
    5.         }
    6.     }
    7. }
    8. console.log(a()()())

    The arrow function doesn't   This, in this function   This only depends on the first function outside him that is not an arrow function   this. In this example, because of the call   a matches the first case in the previous code, so   This is   window. also   Once this is bound to the context, it will not be changed by any code.

    Program reading questions

    1. What is the output of the following program?

    1. function sayHi() {
    2.   console.log(name);
    3.   console.log(age);
    4.    var name =  "Lydia";
    5.   let age =  21;
    6. }
    7. sayHi();
    • A:   Lydia   and   undefined

    • B:   Lydia   and   ReferenceError

    • C:   ReferenceError   and   twenty-one

    • D:   undefined   and   ReferenceError

    Reference answer

    In the function, we first declare the name variable with the var keyword. This means that the variable will be promoted during the creation phase (JavaScript will allocate memory space for the variable during the creation phase), and the default value is undefined until we actually execute the row using the variable. We haven't assigned a value to the name variable yet, so it still maintains the undefined value.

    Variables declared using the let keyword (and const) will also have variable promotion, but unlike var, initialization is not promoted. They are not accessible until we declare (initialize) them. This is called a "temporary dead zone". When we try to access a variable before declaring it, JavaScript throws a ReferenceError.

    How can we use the following example to verify whether there is variable promotion in let

    1. let name =  'ConardLi'
    2. {
    3.   console.log(name)  // Uncaught ReferenceError: name is not defined
    4.   let name =  'code Secret Garden'
    5. }

    If there is no variable promotion for let variable, console.log(name) will output ConardLi, but the result throws ReferenceError. This well shows that let also has variable promotion, but it has a "temporary dead zone", and access is not allowed before variable initialization or assignment.

    The assignment of variables can be divided into three stages:

    • Create variables to open up space in memory

    • Initialize the variable to undefined

    • Real assignment

    About let, var and function:

    • let's "create" process was promoted, but initialization was not promoted.

    • var's "creation" and "initialization" have been promoted.

    • The "creation", "initialization" and "assignment" of function have been promoted.

    2. What does the following code output

    1. var a =  10;
    2. (function () {
    3.     console.log(a)
    4.     a =  5
    5.     console.log(window.a)
    6.      var a =  20;
    7.     console.log(a)
    8. })()

    Output in sequence: undefined - > 10 - > 20

    1. In the immediate execution function, var a = 20; Statement defines a local variable a,because js Variable declaration promotion mechanism, local variable a The declaration of will be promoted to the top of the function body of the immediate execution function, and since such promotion does not include assignment, the first print statement will be printed undefined,The last statement is printed 20.
    2. Because the variable declaration is elevated, a =  5; When this statement is executed, the local variable a It has been declared, so its effect is on local variables a Assignment, at this time window.a It is still the first assignment 10,

    3. What are the following output results?

    1. class Chameleon {
    2.   static colorChange(newColor) {
    3.     this.newColor = newColor;
    4.   }
    5.   constructor({ newColor =  "green" } = {}) {
    6.     this.newColor = newColor;
    7.   }
    8. }
    9. const freddie =  new Chameleon({ newColor:  "purple" });
    10. freddie.colorChange( "orange");
    • A: orange

    • B: purple

    • C: green

    • D: TypeError

    Answer: D

    The colorChange method is static. Static methods exist only in the constructor that created them and cannot be passed to any children. Since freddie is a child object and the function will not be passed, there is no freddie method on the freddie instance: throw TypeError.

    4. When will 1 be output in the following code?

    1. var a = ?;
    2. if(a ==  1 && a ==  2 && a ==  3){
    3.      conso.log( 1);
    4. }

    Reference answer

    Because = = will perform implicit type conversion, we can override the toString method

    1. var a = {
    2.   i:  1,
    3.   toString() {
    4.      return a.i++;
    5.   }
    6. }
    7. if( a ==  1 && a ==  2 && a ==  3 ) {
    8.   console.log( 1);
    9. }

    5. What are the following output results?

    1. var obj = {
    2.      '2':  3,
    3.      '3':  4,
    4.      'length':  2,
    5.      'splice': Array.prototype.splice,
    6.      'push': Array.prototype.push
    7. }
    8. obj.push( 1)
    9. obj.push( 2)
    10. console.log(obj)

    Reference answer

    1. Using the first push, set the push method of obj object   obj[2]=1;obj.length+=1
    2. Use the second push to set the push method of obj object   obj[3]=2;obj.length+=1
    3. When using console.log output, because obj has length attribute and splice method, it is printed as an array
    4. When printing, because the value at subscript 0 and 1 is not set for the array, it is printed as empty, and the active obj[0] is obtained as undefined

    6. What is the output of the following code?

    1. var a = {n:  1};
    2. var b = a;
    3. a.x = a = {n:  2};
    4. console.log(a.x)     
    5. console.log(b.x)

    Reference answer


    First, a and B reference the {n:2} object at the same time, and then execute the a.x = a ={n:2} statement. Although the assignment is correct from right to left, the priority of. Is higher than =. Therefore, executing a.x first here is equivalent to adding an attribute x to the {n:1} object pointed to by a (or b), that is, the object will become {n:1;x:undefined}. Then, the assignment is performed from right to left according to the normal situation. At this time, when a ={n:2} is executed, the reference of a changes and points to the new object {n:2}, while B still points to the old object. Later, when a.x = {n:2} is executed, a will not be parsed again, but the a when a.x was originally parsed, that is, the old object. Therefore, the value of X of the old object is {n:2}, and the old object is {n:1;x:{n:2}, which is referenced by B.
    When outputting a.x later, you have to parse A. at this time, a refers to a of the new object, and the new object has no X attribute, so undefined is output during access; When accessing b.x, the value of X of the old object will be output, that is, {n:2}.

    7. What is the output of the following code?

    1. function checkAge(data) {
    2.    if (data === { age:  18 }) {
    3.     console.log( "You are an adult!");
    4.   }  else  if (data == { age:  18 }) {
    5.     console.log( "You are still an adult.");
    6.   }  else {
    7.     console.log( `Hmm.. You don't have an age I guess`);
    8.   }
    9. }
    10. checkAge({ age:  18 });

    Reference answer

    Hmm.. You don't have an age I guess

    In comparing equality, primitive types are compared by their values, while objects are compared by their references. JavaScript checks whether an object has a reference to the same location in memory.

    The objects we pass as parameters and the objects we use to check for equality are located in different locations in memory, so their references are different.

    That's why {age: 18} = = {age: 18} and   {age: 18} = = {age: 18} return   The reason for false.

    8. What is the output of the following code?

    1. const obj = {  1:  "a",  2:  "b",  3:  "c" };
    2. const set =  new Set([ 1,  2,  3,  4,  5]);
    3. obj.hasOwnProperty( "1");
    4. obj.hasOwnProperty( 1);
    5. set.has( "1");
    6. set.has( 1);

    Reference answer

    true true false true

    All object keys (excluding Symbols) will be stored as strings, even if you don't have a key of a given string type. This is why obj.hasOwnProperty ('1 ') also returns true.

    The above statement does not apply to Set. There is no "1" in our Set: set.has ('1 ') returns false. It has numeric type 1, and set.has (1) returns true.

    9. What is the output of the following code?

    1. // example 1
    2. var a={}, b= '123', c= 123;  
    3. a[b]= 'b';
    4. a[c]= 'c';  
    5. console.log(a[b]);
    6. ---------------------
    7. // example 2
    8. var a={}, b=Symbol( '123'), c=Symbol( '123');  
    9. a[b]= 'b';
    10. a[c]= 'c';  
    11. console.log(a[b]);
    12. ---------------------
    13. // example 3
    14. var a={}, b={key: '123'}, c={key: '456'};  
    15. a[b]= 'b';
    16. a[c]= 'c';  
    17. console.log(a[b]);

    Reference answer

    This problem examines the conversion of key names of objects.

    • Object key names can only be string and Symbol types.

    • Other types of key names are converted to string types.

    • Object to string will call the toString method by default.

    1. // example 1
    2. var a={}, b= '123', c= 123;
    3. a[b]= 'b';
    4. //  c   The key name will be converted to the string '123', where b will be overwritten.
    5. a[c]= 'c';  
    6. //  output   c
    7. console.log(a[b]);
    8. // example 2
    9. var a={}, b=Symbol( '123'), c=Symbol( '123');  
    10. // b is a Symbol type and does not require conversion.
    11. a[b]= 'b';
    12. // c is a Symbol type and does not require conversion. The values of any Symbol type are not equal, so b will not be overwritten.
    13. a[c]= 'c';
    14. //  output   b
    15. console.log(a[b]);
    16. // example 3
    17. var a={}, b={key: '123'}, c={key: '456'};  
    18. // b is neither a string nor a Symbol type. It needs to be converted to a string.
    19. //  The object type will call the toString method to convert to a string   [object Object].
    20. a[b]= 'b';
    21. // c is neither a string nor a Symbol type. It needs to be converted to a string.
    22. //  The object type will call the toString method to convert to a string   [object Object]. b will be covered here.
    23. a[c]= 'c';  
    24. //  output   c
    25. console.log(a[b]);

    10. What is the output of the following code?

    1. (() => {
    2.   let x, y;
    3.   try {
    4.     throw  new Error();
    5.   } catch (x) {
    6.     (x =  1), (y =  2);
    7.     console.log(x);
    8.   }
    9.   console.log(x);
    10.   console.log(y);
    11. })();

    Reference answer

    1 undefined 2

    The catch block receives parameter X. When we pass parameters, this is different from the X of the variable. This variable x belongs to the scope of catch.

    After that, we set the variable of this block level scope to 1 and set the value of variable y. Now, let's print the variable x of the block level scope, which is equal to 1.

    Outside the catch block, X is still undefined and y is 2. When we want console.log(x) outside the catch block, it returns undefined and y returns 2.

    11. What is the output of the following code?

    1. function Foo() {
    2.     Foo.a = function() {
    3.         console.log( 1)
    4.     }
    5.     this.a = function() {
    6.         console.log( 2)
    7.     }
    8. }
    9. Foo.prototype.a = function() {
    10.     console.log( 3)
    11. }
    12. Foo.a = function() {
    13.     console.log( 4)
    14. }
    15. Foo.a();
    16. let obj =  new Foo();
    17. obj.a();
    18. Foo.a();

    Reference answer

    The output order is 4 2 1

    1. function Foo() {
    2.     Foo.a = function() {
    3.         console.log( 1)
    4.     }
    5.     this.a = function() {
    6.         console.log( 2)
    7.     }
    8. }
    9. //  Above just   Foo   The construction method of does not generate an instance and is not executed at the moment
    10. Foo.prototype.a = function() {
    11.     console.log( 3)
    12. }
    13. //  Now in   Foo   The prototype method is mounted on the   a  , Method output value is   three
    14. Foo.a = function() {
    15.     console.log( 4)
    16. }
    17. //  Now in   Foo   The direct method is mounted on the   a  , The output value is   four
    18. Foo.a();
    19. //  Immediately   Foo   Upper   a   Method, which is just defined, so
    20. // #  output   four

    Source: misty rain life V


Tags: Javascript Front-end

Posted on Tue, 02 Nov 2021 06:58:14 -0400 by shlumph