web123456

Front-end classic interview questions (60 front-end interview questions including JS, CSS, React, Web, Browser, Programming questions, etc.)

Author:Still Watching the Flowing Leaves

Original address: /s/PTSaytcf3xgOp6C9l3Pvjw

short answer

1、What is stabilization and throttling? What is the difference? How to realize?

reference answer

anti-shake

The function will be executed only once in n seconds after the HF event is triggered, and the time will be recalculated if the HF event is triggered again in n seconds.

  • Thoughts:

Cancel the previous delayed call method each time the event is triggered

  1. function debounce(fn) {
  2.       let timeout = null// Create a tag to hold the timer's return value
  3.       return function () {
  4.         clearTimeout(timeout); // Clear the previous setTimeout every time the user enters it
  5.         timeout = setTimeout(() => { // Then create a new setTimeout, which ensures that the fn function won't be executed if any more characters are typed in the interval between inputs
  6.           fn.apply(thisarguments);
  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

weir valve

High-frequency events are triggered, but will only execute once in n seconds, so throttling dilutes the function's execution frequency

  • Thoughts:

Each time an event is triggered, determine if there is a delayed function waiting to be executed.

  1. function throttle(fn) {
  2.       let canRun = true// Saving a token through a closure
  3.       return function () {
  4.         if (!canRun) return// Determine at the beginning of the function if the marker istruenot fortrueimitatereturn
  5.         canRun = false// Immediately set tofalse
  6.         setTimeout(() => { // Place the execution of externally passed functions in setTimeout
  7.           (this, arguments);
  8.           // Finally, after setTimeout has finished executing then set the marker to thetrue(key) indicates that the next loop can be executed now. When the timer is not executed the marker is alwaysfalseThe beginning of the program has beenreturnlose (value, weight etc)
  9.           canRun = true;
  10.         }, 500);
  11.       };
  12.     }
  13.     function sayHi(e) {
  14.       (, );
  15.     }
  16.     ('resize', throttle(sayHi));

2, get request pass parameter length of the misunderstanding, get and post request in the cache difference

Myth: We often say that there is a limit to the size of a get request parameter, while there is no limit to the size of a post request parameter.

reference answer

The HTTP protocol never actually specifies what the request length limit for GET/POST is. The limitations on the get request parameters come from the browser or web server, which limits the length of the url. To clarify this concept, we must re-emphasize the following points.

  • The HTTP protocol does not specify length limits for GET and POST.

  • The maximum length of a GET is shown because browsers and web servers limit the length of URIs.

  • Different browsers and web servers have different maximum lengths.

  • To support IE, the maximum length is 2083byte, if only Chrome is supported, the maximum length is 8182byte

Add add a difference between get and post in terms of caching:

  • A get request is similar to a lookup process, where the user gets the data without having to connect to the database each time, so caching can be used.

  • Unlike post, post does generally modify and delete work, so it must interact with the database, so it cannot use cache. Therefore get requests are suitable for request caching.

3. Modularization development history

Available from IIFE, AMD, CMD, CommonJS, UMD,webpack()、ES Module、<script type="module"> These are a few perspectives to consider.

reference answer

Modularity is mainly used to abstract public code, isolate scopes, avoid variable conflicts, etc.

IIFE: Use self-executing functions to write modularity, features:Execute code in a separate function scope to avoid variable conflicts

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

AMD: Use requireJS to write modular, features:Dependencies must be declared well in advance

  1. define('./',function(code){
  2.     // code just likeindex.js Returns
  3. })

CMD: Use seaJS to write modularity, features:Support for dynamic introduction of dependency files

  1. define(function(requireexportsmodule) {  
  2.   var indexCode = require('./');
  3. })

CommonJS: Modularity comes with nodejs.

var fs = require('fs');

UMD: AMD-compatible, CommonJS modular syntax.

webpack(): Code splitting in the webpack version.

ES Modules: Modularity introduced by ES6 supports import to bring in another js.

import a from 'a';

4、npmModule installation mechanism,Why do you enter npm installThe corresponding module can be installed automatically?

reference answer

1. npm module installation mechanism:

  • issue (an order, decree etc)npm installcommand

  • Check if the module already exists in the node_modules directory.

    • npm queries the registry for the URL of the module package.

    • Download the zip file and store it in the root directory of the.npmdirectory

    • Extract the zip to the current project'snode_modulescatalogs

    • If it exists, it will not be reinstalled

    • If not present

2. npm implementation principle

After typing the npm install command and hitting enter, you will go through the following stages (using npm 5.5.1 as an example):

  1. Execute the project itself preinstall

    The preinstall hook will be executed if it is defined in the current npm project.

  2. Identify first-level dependency modules

    The first thing you need to do is identify the first-level dependencies in your project, which are the modules specified directly in the dependencies and devDependencies attributes (assuming you haven't added the npm install parameter at this point).

    The project itself is the root node of the dependency tree, and each first-level dependency module is a subtree below the root node. npm will start a multi-process to gradually find deeper nodes from each first-level dependency module.

  3. Getting the module

    Getting a module is a recursive process, divided into the following steps:

    • Getting module information. Before downloading a module, you first need to determine its version, because semantic versions are often found in the module's version description file (or ). In this case, if the version description file ( or ) has the module information, you can get it directly, if not, you can get it from the repository. For example, if the version of a package in ^1.1.0 is ^1.1.0, npm will go to the repository and get the latest version that matches the form.

    • Get the module entity. In the previous step, you will get the address of the module's tarball (resolved field). npm will use this address to check the local cache, and if there is one in the cache, you can get it directly, if not, you can download it from the repository.

    • Find the module dependencies and go back to step 1 if there are any, or stop if there are none.

  4. Module flattening (dedupe)

    The previous step fetched a complete dependency tree, which may contain a large number of duplicate modules, e.g. module A depends on loadsh. For example, module A depends on loadsh, and module B also depends on lodash. npm3 used to follow the structure of the dependency tree very closely, which led to module redundancy.

    Since npm3, a dedupe process has been added by default. It iterates through all the nodes, placing modules one by one under the root node, which is the first level of node-modules. When it finds arepetitive moduleWhen it does, it is discarded.

    There is a need here for therepetitive moduleTo make a definition, it refers tomodule name is the sameboth (... and...)semver compatibility. Each semver corresponds to a range of version allowances, and if there is an intersection of the version allowances of the two modules, then we get a compatibilityversion without having to have identical version numbers, which allows more redundant modules to be removed during the dedupe process.

    For example, if the foo module under node-modules depends on lodash@^1.0.0, and the bar module depends on lodash@^1.1.0, then the^1.1.0 for compatible versions.

    When foo depends on lodash@^2.0.0 and bar depends on lodash@^1.1.0, then according to semver's rules, there is no compatible version for both. One version is placed in node_modules and the other remains in the dependency tree.

    As an example, suppose a dependency tree originally looked like this:

    node_modules -- foo ---- lodash@version1

    -- bar ---- lodash@version2

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

    node_modules -- foo

    -- bar

    -- lodash (retained versions are compatible)

    Assuming that version1 and version2 are non-compatible, the later versions are kept in the dependency tree:

    node_modules -- foo -- lodash@version1

    -- bar ---- lodash@version2

  5. mounting module

    This step will update the node_modules in the project and execute the lifecycle functions in the module (in the order preinstall, install, postinstall).

  6. Implementing the engineering life cycle itself

    The current npm project will execute the hooks if they are defined (in the order of install, postinstall, prepublish, prepare).

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

5、What is the difference between ES5 inheritance and ES6 inheritance?

reference answer

ES5 inheritance is implemented through the prototype or constructor mechanism.ES5 inheritance essentially creates the instance object of the subclass and then adds the parent class's methods to this((this))。

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

Specific: ES6 defines classes via class keyword with constructor methods inside and inheritance between classes via extends keyword. Subclasses must call the super method in the constructor method, otherwise the new instance reports an error. This is because the subclass does not have its own this object, but inherits the parent class's this object and then processes it. If the super method is not called, the subclass does not get the this object.

ps: The super keyword refers to an instance of the parent class, i.e., the parent class' this object. In the subclass constructor, the this keyword can be used only after calling super, otherwise an error is reported.

6. setTimeout, Promise, Async/Await differences

reference answer

7. Timer execution order or mechanism?

reference answer

**Because js is single-threaded, the browser encounters setTimeout or setInterval will be the first to execute the current block of code, before the timer will be pushed into the browser's queue of events to be executed, until the browser is finished executing the current code, it will take a look at the event queue inside there is no task, there is a timer if the code is executed. ** So even if you set the timer to 0, you will still execute the current code first.

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

Output results:

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

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

reference answer

Output:[1, NaN, NaN]

  • Let's start by recalling that the map function takes a callback as its first argument:

var new_array = (function callback(currentValue[, index[, array]]) { // Return element for new_array }[, thisArg])This callback can take a total of three arguments, the first of which represents the element currently being processed, while the second represents the index of that element.

  • Instead, parseInt is used to parse the string so that the string becomes an integer with the specified base.parseInt(string, radix)Receives two arguments, the first representing the value (string) being processed and the second representing the base for parsing.

  • Knowing these two functions, we can simulate the operation

  1. parseInt('1', 0) //When radix is 0, and string parameter does not start with "0x" and "0", it will be processed according to base 10. This time return 1

  2. parseInt('2', 1) // the maximum value of the number expressed in base 1 (binary 1) is less than 2, so it can't be parsed, return NaN

  3. parseInt('3', 2) // the maximum value of the number expressed in base 2 (binary) is less than 3, so it can't be parsed, return NaN

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

9, Doctype role? How to distinguish between strict mode and mixed mode? What is their significance?

reference answer

Doctype is declared at the top of the document and tells the browser which way to render the page, there are two modes here, strict mode and mixed mode.

  • Strict-mode typography and JS modes of operation run at the highest standards supported by the browser.

  • Mixed mode, backward compatible, emulates older browsers and prevents browsers from not being able to compatible with the page.

10. fetch sends 2 requests for a reason

reference answer

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

The reason is simple, because your post request with fetch causes fetch to send an Options request the first time, asking the server if it supports modified request headers, and if it does, sending the real request in the second time.

http, browser object

1、HTTPS handshake process, the client how to verify the legitimacy of the certificate

reference answer
  • First of all what is the HTTP protocol?

    http protocol is a hypertext transfer protocol, located in the tcp/ip four-layer model in the application layer; through the request/response way between the client and the server for communication; but the lack of security, http protocol information transfer is transmitted in the clear text, do not do any encryption, the equivalent of the network running naked; easy to be maliciously tampered with by the intermediary, this behavior is called man-in-the-middle attack;

  • Encrypted communication:

    For security, the two sides can use symmetric encryption key for information exchange, but this way symmetric encryption secret key will also be intercepted, also not secure enough, and then there is still a risk of being attacked by the intermediary; so people have come up with another way to use asymmetric encryption; the use of public/private encryption and decryption; the communication party A initiates the communication and carries its own public key, and the receiver B encrypts symmetric secret key through the public key to encrypt the symmetric secret key; and then sent to the initiator A; A decrypted through the private key; double sent next through the symmetric secret key to encrypted communication; but this way there will still be a kind of security; although the intermediary does not know the initiator of the A's private key, but it can be done to sneak in the sky, will intercept the initiator of the public key key; and will be their own generation of a pair of public/private key of the public key to send to the B; the receiver of the B does not know that the public key has been secretly changed; according to the previous process, B encrypts the symmetric encryption secret key key2 generated by himself through the public key; sends it to A; this time the communication is again intercepted by the intermediary, although the later communication, the two are still communicating with the key2, but the intermediary has already mastered the Key2; it can be easy to encrypt and decrypt; there is still a risk of being attacked by the intermediary;

  • Solve the dilemma: authoritative certificate authority CA to solve;

    • Production of certificates: as a server-side A, first of all, their own public key key1 to the certificate authority to apply for certificates to the certificate authority; certificate authority has a set of its own public and private keys, CA through its own private key to encrypt key1, and through the server-side Web site and other information to generate a certificate signature, certificate signature is also used to encrypt the agency's private key; after the completion of the production of the agency will be certificate to A;

    • Verify the authenticity of the certificate: when B initiates a request communication to the server A, A no longer returns its own public key directly, but returns a certificate;

Description: major browsers and operating systems have maintained all the authoritative certificate authority's name and public key. b only need to know which authority issued the certificate, using the corresponding agency's public key, you can decrypt the certificate signature; next, b use the same rules, to generate their own certificate signature, if the two signatures are the same, indicating that the certificate is valid; the signature is verified successfully, b can once again use the public key of the organization, decrypt the public key key1 of A; the next operation, it is the same process as before;

  • Does the intermediary intercept the sending of fake certificates to B?

Because the signature of the certificate is generated by the server-side URL and other information, and encrypted by the third-party organization's private key intermediary can not be tampered with; so the most critical issue is the authenticity of the certificate signature;

  • The main idea of https is to add a ssl security layer on top of http, i.e. the above authentication process;

2. TCP three handshakes and four waves

reference answer

The reason for the three handshakes is that it is the minimum number of times that both client and server are guaranteed to let each other know that their ability to receive and send is okay.

The first time client => server only server can determine the client has the ability to send the second server => client client can determine the server has the ability to send and receive. At this point, the client also needs to let the server know that its ability to receive is okay, so there is a third time Third time client => server Both parties have ensured that their ability to receive and send is okay

Among other things, to ensure that subsequent handshakes are in response to the previous handshake, each handshake carries an identifier seq, and subsequent ACKs are acknowledged by adding one to this seq.

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

reference answer
  • iframe

Pros: After the cross-domain is complete DOM manipulation and mutualJavaScriptThe calls are all fine.

Disadvantages: 1. If the result is to be passed as a URL parameter, it means that when the result is a large amount of data, it needs to be divided and passed, which is very annoying. 2. There is also an iframe itself, which is brought about by the interaction between the mother page and the iframe itself, which has its own security restrictions.

  • script

Advantage: can directly return data in json format, easy to handle

Disadvantage: only accepts GET request method

  • Image ping

Advantages: can access any url, generally used for click tracking, do page analysis commonly used methods

Disadvantages: can not access the response text, can only listen to whether the response

4. The difference between http and https?

reference answer

The data transmitted by http are unencrypted, that is, plaintext, Netscape set up SSL protocol to encrypt the data transmitted by the http protocol. Simply put, the https protocol is a network protocol that can be encrypted for transmission and authentication constructed by the http and ssl protocols, and it is more secure than the http protocol. The main differences are as follows:

  • The Https protocol requires a ca certificate, which is more expensive.

  • http is a hypertext transfer protocol where information is transmitted in clear text and https is an ssl encrypted transfer protocol with security.

  • Using different linking methods, the port is also different, generally speaking, the port of the http protocol is 80, https port 443

  • The connection of http is simple and stateless; HTTPS protocol is a network protocol that can be used for encrypted transmission and authentication built by SSL+HTTP protocol, which is more secure than http protocol.

5. What is Bom and what are the common Bom properties?

reference answer

Bom is a browser object

Location object

  • -- Returns or sets the URL of the current document

  • -- Returns the query string portion of the URL. For example /dreamd... Returns the part of the query string that includes the (?) followed by ?id=5&name=dreamdu

  • -- Returns the content following the URL #, or null if there is no # -- Returns the domain name portion of the URL, for example

  • -- Returns the main domain name portion of the URL, e.g.

  • -- Returns the part of the URL after the domain name. For example /xhtml/ returns /xhtml/

  • -- Returns the port portion of the URL. For example :8080/xhtml/ returns 8080

  • -- Returns the protocol portion of the URL. For example :8080/xhtml/ Returns what precedes (//) http.

  • -- Set the URL of the current document

  • () -- sets the URL of the current document and removes it from the list of addresses in the history object (url).

  • () -- reloads the current page

history object

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

  • (num); () -- one page back

  • () -- one page forward

Navigator object

  • -- Returns a string representation of the user agent header (that is, a string that includes browser version information, etc.).

  • -- Returns whether the browser supports (enables) cookies.

6、Difference between Cookie, sessionStorage, localStorage

reference answer

The common denominator: both are saved on the browser side and are homogenous

  • Cookie: Cookie data is always carried in the same source http request (even if it is not needed), i.e., the cookie is passed back and forth between the browser and the server. SessionStorage and localStorage will not automatically send the data to the server, only in the local storage. cookie data also has the concept of path, you can limit the cookie only belongs to a certain path, the size of the storage is very small only about 4K. (key: can be passed back and forth between the browser and the server, the storage capacity is small, only about 4K or so)

  • sessionStorage: only valid before the current browser window is closed, naturally it is not possible to keep it persistently, localStorage: always valid, the window or the browser is closed also has been saved, so it is used as persistent data; cookie is only valid until the cookie expiration time is set, even if the window or the browser is closed. (key: itself is a talkback process, disappears after closing the browser, session is a talkback, when the page is different even if the same page is opened twice, it is regarded as the same talkback)

  • localStorage: localStorage is shared among all same-origin windows; cookie is also shared among all same-origin windows. (key: shared across all homologous windows and will not expire, always works regardless of window or browser closure)

Add a note about the role of cookies:

  • Save the user's login status. For example, storing the user id in a cookie eliminates the need for the user to log in again the next time they visit the page, a feature that many forums and communities now offer. cookies can also be set to expire after a certain period of time, so that they will automatically disappear. Therefore, it is often possible to prompt the user to stay logged in for a certain period of time: one month, three months, one year, etc. are common options.

  • Tracking user behavior. For example, a weather forecasting website can display local weather conditions based on the region selected by the user. It would be tedious to have to choose a location every time, but when cookies are utilized, it becomes very user-friendly. The system remembers the last area visited, and when the page is opened the next time, it automatically displays the weather for the area where the user was located the last time. Because everything is done in the background, the page is customized for the user and is very easy to use!

  • Customizing pages. If the site offers the ability to skin or change the layout, then cookies can be used to record the user's options, e.g. background color, resolution, etc. When the user visits next time, the interface style of the previous visit can still be saved.

7, Cookie how to prevent XSS attacks

reference answer

XSS (Cross Site Scripting Attacks) is when an attacker embeds a javascript script in the returned HTML. To mitigate these attacks, it is necessary to match the HTTP header with a, set-cookie:

  • httponly-This attribute prevents XSS, it disables javascript from accessing the cookie.

  • secure - This attribute tells the browser to send a cookie only if the request is https.

The result should look like this: Set-Cookie=.....

8、Difference between browser and Node event loop?

reference answer

One of the main differences is that the browser's event loop and nodejs event loop in the processing of asynchronous events in a different order, nodejs micro event; which Promise belongs to the micro event the asynchronous event processing order and the browser is different. nodejs V11.0 or above this nodejs V11.0 and above, the order between the two is the same.

  1. function test () {
  2.    ('start')
  3.     setTimeout(() => {
  4.         ('children2')
  5.         ().then(() => {('children2-1')})
  6.     }, 0)
  7.     setTimeout(() => {
  8.         ('children3')
  9.         ().then(() => {('children3-1')})
  10.     }, 0)
  11.     ().then(() => {('children1')})
  12.     ('end'
  13. }
  14. test()
  15. // The above code in the node11Execution results for the following version (all macrotasks are executed first, then microtasks)
  16. // start
  17. // end
  18. // children1
  19. // children2
  20. // children3
  21. // children2-1
  22. // children3-1
  23. // The above code in the node11and browser execution results (sequential execution of macrotasks and microtasks)
  24. // start
  25. // end
  26. // children1
  27. // children2
  28. // children2-1
  29. // children3
  30. // children3-1

9. Briefly describe the HTTPS man-in-the-middle attack

reference answer

The https protocol consists of the http + ssl protocols, and the specific linking process can be summarized in the SSL or TLS handshake

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

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

  2. The attacker intercepts the public key and keeps it for himself.

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

  4. The client receives the forged public key and generates an encrypted hash value to send to the server.

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

  6. A fake encrypted hash value is also generated and sent to the server.

  7. The server decrypts the private key to obtain the fake secret key.

  8. The server transmits the information encrypted with an encrypted key

Precautionary approach:

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

10, say a few web front-end optimization strategies

reference answer

(1). Reduce the number of HTTP requests

This strategy is known to basically all front-end people, and it's also the most important and effective. We all say we need to reduce HTTP requests, but what happens when there are more requests? First of all, each request has a cost, including both time and resource costs. A complete request needs to go through the DNS addressing, and the server to establish a connection, send data, wait for the server to respond, receive data such a "long" and complex process. The time cost is that the user needs to see or "feel" the resource is necessary to wait for the end of the process, resources, because each request needs to carry data, so each request needs to take up bandwidth.

In addition, because the browser for concurrent requests is an upper limit on the number of requests, so the number of requests, the browser needs to request in batches, so it will increase the user's waiting time, which will give the user the impression that the site is slow, even though the user may be able to see the first screen of the resources have been requested, but the browser's progress bar will always be there. The main ways to reduce the number of HTTP requests include:

(2). Simplifying pages at the design implementation level

If your page is as simple as the front page of Baidu, then the next rules are basically useless. Keeping the page simple and minimizing the use of resources is the most straightforward. If that's not the case and your page needs a flashy skin, then continue reading below.

(3). Reasonable setting of HTTP cache

The power of caching is powerful, appropriate cache settings can greatly reduce HTTP requests. To have ah home page, for example, when the browser is not cached when accessing a total of 78 requests will be issued, a total of more than 600K data (Figure 1.1), and when the second visit that the browser has been cached after accessing only 10 requests, a total of more than 20K data (Figure 1.2). (Here it should be noted that, if the direct F5 refresh page is not the same, the number of requests in this case is still the same, but the cached resource request server is a 304 response, only the Header does not have a Body, you can save bandwidth)

What is a reasonable setting? The principle is simple: the more you can cache, the better; the longer you can cache, the better. For example, rarely changing image resources can be directly through the HTTP Header Expires set a very long expiration header; infrequent changes and may change the resources can use Last-Modifed to do request validation. As much as possible, resources can stay in the cache for a longer period of time.

(4). Resource consolidation and compression

If possible, as far as possible to merge the external scripts, styles, multiple into one. In addition, CSS, Javascript, Image can be compressed with the appropriate tools, compression can often save a lot of space.

(5). CSS Sprites

Another great way to reduce the number of requests by merging CSS images.

(6). Inline Images

Embedding images into a page or CSS using a data: URL scheme is a good idea if you don't have resource management issues. Embedding in a page will increase the size of the page and will not utilize browser caching. Using images in CSS is more desirable.

(7). Lazy Load Images

This policy doesn't 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 loading. In the case of images, it is possible to load only the first screen when the page first loads, and only load the subsequent images as the user scrolls back. In this way, if the user is only interested in the content of the first screen, the remaining image requests are saved. The practice of the home page of Yauah used to be to cache the address of the image after the first screen in the Textarea tag when loading, and load it only when the user scrolls down the screen in an "inert" way.

11. What you know about performance issues caused by browser redraw and reflow

reference answer

Repaint and Reflow

Redraw and reflow are a small part of the rendering step, but they have a big impact on performance.

  • Redrawing is used when a node needs to change its appearance without affecting the layout, such as changing thecolorIt's called a redraw.

  • Reflows are called reflows when layout or geometric properties need to be changed.

Reflows are bound to occur with redraws, and redraws do not necessarily trigger reflows. Reflows require much higher costs than redraws, and changing deep nodes is likely to lead to a series of reflows in the parent node.

So here are a few actions that may cause performance issues:

  • Change window size

  • Change font

  • Adding or Removing Styles

  • textual change

  • Position or float

  • box model

What many people don't realize is that redraw and reflow are actually related to Event loops.

  1. When the Event loop finishes executing the Microtasks, it determines if the document needs to be updated. Because the browser has a 60Hz refresh rate, the document is updated every 16ms.

  2. Then determine whether theresizeorscrollIf it does, it will go and trigger the event, soresizecap (a poem)scrollThe event is also triggered at least once every 16ms and comes with a throttling feature.

  3. Determines if a media query has been triggered

  4. Update animation and send events

  5. Determine if there is a full-screen action event

  6. fulfillmentrequestAnimationFramepull back (of a key (in music)

  7. fulfillmentIntersectionObservercallback, this method is used to determine whether an element is visible or not, can be used on lazy loading, but compatibility is not good

  8. Updating the interface

  9. These are the things that may be done in a frame. If there is free time in a frame, it will go ahead and perform therequestIdleCallbackCallback.

Reduce redraws and reflows

  • utilizationtranslate substitute fortop

    1. <div class="test"></div>
    2. <style>
    3.     .test {
    4.         position: absolute;
    5.         top10px;
    6.         width: 100px;
    7.         height: 100px;
    8.         background: red;
    9.     }
    10. </style>
    11. <script>
    12.     setTimeout(() => {
    13.         // cause reflux
    14.         ('.test').style.top = '100px'
    15.     }, 1000)
    16. </script>
  • utilizationvisibilityinterchangeabilitydisplay: none, because the former only causes a redraw and the latter triggers a reflow (which changes the layout)

    Modify the DOM offline, e.g. first give the DOM to thedisplay:none(with one Reflow) and then you modify it 100 times and then show it again

    Don't put DOM node attribute values in a loop as variables in the loop.

    1. for(let i = 0; i < 1000; i++) {
    2.     // Getting the offsetTop will cause a reflow because you need to get the correct value.
    3.     (('.test').)
    4. }
  • Don't use table layout, a small change may cause the whole table to be rearranged.

  • The choice of the speed at which the animation is realized, the faster the animation, the higher the number of reflows, and also the option to use therequestAnimationFrame

  • CSS selectors match from right to left to avoid too deep DOM.

  • Turn frequently running animations into layers, which prevent the node from flowing back to affect other elements. For example, for thevideotag, the browser will automatically turn the node into a layer.

react、Vue

1、When writing a React / Vue project, why do you need to write the key in the list component and what is its role?

reference answer

Both vue and react use diff algorithm to compare the old and new virtual nodes to update the nodes. In vue's diff function (it is recommended to understand the diff algorithm process first). In the cross-comparison, when the new node is compared with the old nodehead-to-tail cross-referenceWhen there are no results, the key of the new node is compared to the key in the old node array to find the corresponding old node (which here corresponds to a map mapping of key => index). If it is not found, it is considered a new node. If there is no key, then a traversal is used to find the corresponding old node. One is a map-mapping, the other is a traversal lookup. In comparison, map mapping is faster. vue part of the source code is as follows:

  1. // vue project src/core/vdom/  -488classifier for objects in rows such as words
  2. // Here is the code formatted 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
  9.   idxInOld = oldKeyToIdx[newStartVnode.key]
  10. else {
  11.   // Iteration to get
  12.   idxInOld = findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)
  13. }

Creating a 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. }

Iterative search

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

2、When is setState synchronous and when is it asynchronous in React?

reference answer

In React.In the case of event processing triggered by React (e.g. via onClick), the call to setState will not be updated synchronously, other than that the setState call will be performed synchronouslyThe "other than" refers to event handlers that bypass React's direct addEventListener and asynchronous functions generated by setTimeout/setInterval. By "other than", I mean event handlers that bypass React's addEventListener and asynchronous calls generated by setTimeout/setInterval.

**Reason:** In React's implementation of the setState function, it will be based on a variable isBatchingUpdates to determine whether to update directly or put it into the queue to go back and talk about it, and isBatchingUpdates is false by default, which means that the setState will be updated in a synchronized way, however, theThere is a function batchedUpdates, this function will change isBatchingUpdates to true, and when React will call this batchedUpdates before calling the event handler function, resulting in the consequence that the event handler setState, which is controlled by React, will not be synchronized with updates

3. What is output below

  1. class Example extends React.Component {
  2.   constructor() {
  3.     super();
  4.     this.state = {
  5.       val0
  6.     };
  7.   }
  8.   
  9.   componentDidMount() {
  10.     this.setState({valthis.state.val + 1});
  11.     (this.state.val);    // 1st log
  12.     this.setState({valthis.state.val + 1});
  13.     (this.state.val);    // 2nd log
  14.     setTimeout(() => {
  15.       this.setState({valthis.state.val + 1});
  16.       (this.state.val);  // 3rd log
  17.       this.setState({valthis.state.val + 1});
  18.       (this.state.val);  // 4th log
  19.     }, 0);
  20.   }
  21.   render() {
  22.     return null;
  23.   }
  24. };
  25. 1The first and second are within the react lifecycle, and isBatchingUpdates when triggered istrueInstead of updating the state directly, dirtyComponents is added so that the printout gets the state before the update.0
  26. 2When you setState twice, you will get thethis.state.val all0So the execution is all about putting the0 set to1, which will be merged out inside react and executed only once. After the setup is complete state.val be valued at1
  27. 3The code in the setTimeout isBatchingUpdates when triggered.falseSo the update can be done directly, so the output is linked to the23
  28. Output:0 0 2 3

4. Why does virtual dom improve performance?

reference answer

Virtual dom is equivalent to adding a cache in the middle of the js and real dom , using dom diff algorithm to avoid unnecessary dom operation , thus improving performance .

The steps to achieve this are as follows:

Represent the structure of the DOM tree as a JavaScript object structure; then use this tree to build a real DOM tree and insert it into the document.

When the state changes, a new object tree is reconstructed. The new tree is then compared to the old one, and the differences between the two trees are recorded.

Applying the differences recorded in 2 to the real DOM tree constructed in step 1, the view is updated.

css

1, analyze and compare opacity: 0, visibility: hidden, display: none advantages and disadvantages and applicable scenarios

reference answer

structure: display:none: will make the element disappear from the render tree completely, the rendered element does not occupy any space, cannot be clicked, visibility: hidden: will not make the element disappear from the render tree, the rendered element continues to occupy space, just the content is not visible, cannot be clicked opacity: 0: will not make the element disappear from the render tree, the rendered element continues to occupy space, just the content is not visible and can be clicked.

Inheritance: display: none: is a non-inherited attribute, the disappearance of the descendant nodes is caused by the disappearance of the element from the render tree, and cannot be displayed by modifying the attributes of the descendant nodes. visibility: hidden: is an inherited attribute, the disappearance of the descendant nodes is caused by the inheritance of hidden, and can be made visible by setting the visibility: visible; to make the descendant nodes visible.

Performance: displaynone: modify the element will cause the document to reflow, the screen reader will not read the content of the display: none element, the performance consumption is larger visibility: hidden: modify the element will only cause the element to redraw, the performance consumption is less screen reader to read the content of the visibility: hidden element opacity: 0 : modify the element will cause redrawing, the performance consumption is less screen reader to read the content of the opacity: 0 : modify the element will cause redrawing, the performance consumption is less screen reader to read the content of the visibility: hidden element 0: modifying the element will cause redrawing, less performance consumption

Connection: they both make elements invisible

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

reference answer

There are three general types in common use.clearfixclear:both,overflow:hidden;

Better yet..clearfixPseudo-elemental jack-of-all-trades versions, the latter two having limitations.

  1. .clearfix:after {
  2.   visibility: hidden;
  3.   display: block;
  4.   font-size0;
  5.   content" ";
  6.   clear: both;
  7.   height0;
  8. }
  9. <!--
  10. Why don't you have zoom,_height, IE6, _height, _height, _height, _height, _height and _height?7The need for a csshack is no longer a concern.
  11. .clearfix There's another way to write it.
  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. expense or outlaydisplay:table is to avoid margin collapse caused by overlapping margins.
  26. Internal elements become table-cells by default.
  27. -->

clear:both: It's good if it's used on neighboring elements in the same container, but sometimes it's problematic when it's outside of the container, such as collapsing the wrapper elements of neighboring containers.

overflow:hiddenThis can be formed if used in the same container.BFCAvoid collapsing elements caused by floats

4, css sprite is what, what are the advantages and disadvantages

reference answer

Concept: Stitch multiple small images into one image. The background-position and element size adjust the background pattern to be displayed.

Pros:

  1. Reduces the number of HTTP requests and dramatically improves page load speeds

  2. Increase image information repetition, improve compression ratio, reduce image size

  3. Easy to change the style, just change the color or style on one or several pictures to achieve

Drawbacks:

  1. Trouble merging images

  2. Maintenance hassles, modifying an image may require re-layout of the entire image, style

5、linktogether with@importexclusionary rule

reference answer
  1. linkis in HTML.@importIt's the CSS way.

  2. linkMaximum support for parallel downloads.@importToo much nesting leads to serial downloads and FOUCs

  3. linkThis can be done byrel="alternate stylesheet"Specify Candidate Style

  4. browser's view oflinkSupported earlier than@importYou can use the@importHide styles for older browsers

  5. @importIt is possible to refer to other files in the css file before the style rule

  6. Overall:link is superior to @import

6、display: block;cap (a poem)display: inline;exclusionary rule

reference answer

blockElemental Characteristics:

1. When in regular flow, if thewidthNo setting, will automatically fill the parent container 2. can be appliedmargin/padding 3. extends the height to include child elements in the regular flow if the height is not set 4. between the front and back element positions when laid out in the regular flow (occupies a horizontal space exclusively) 5. ignoredvertical-align

inlineElemental Characteristics

1. Horizontally according todirectionarrange in order

2. Will not do line breaks before and after the element

3. Subject towhite-spacecontainment

4.margin/paddingInvalid in the vertical direction, valid in the horizontal direction

5.width/heightattribute does not work for non-replaced inline elements, the width is determined by the content of the element

6. The height of the line box for non-replaced inline elements is determined by theline-heightdetermines that the line box height of the replacement in-line element is determined by theheight,margin,padding,borderDecision 7. Float or absolute positioning will be converted toblock8.vertical-alignAttributes take effect

7, the container contains a number of floating elements when how to clean up the float

reference answer
  1. Adds an extra element before the container element closure tag and sets theclear: both

  2. The parent element triggers the block-level formatting context (see the section on block-level visualization contexts)

  3. Setting up container elements pseudo-elements for cleanup Recommended methods for cleaning up floats

  1. /**
  2. * Use in standard browsers
  3. * 1 contentThe content of the space is used to fix a document under opera that has a
  4. * The contenteditable attribute clears up whitespace above and below a floating element.
  5. * 2 utilizationdisplayutilizationtablerather thanblock: It is possible to prevent the container and
  6. * The child element top-margin collapses, which makes the cleanup effect the same as BFC, IE6/7
  7. *   zoom: 1; Consistency
  8. **/
  9. .clearfix:before,
  10. .clearfix:after {
  11.     content" "/* 1 */
  12.     displaytable/* 2 */
  13. }
  14. .clearfix:after {
  15.     clear: both;
  16. }
  17. /**
  18. * IE 6/7under the jurisdiction of
  19. * Include floats by triggering hasLayout
  20. **/
  21. .clearfix {
  22.     *zoom: 1;
  23. }

8、PNG,GIF,JPG difference and how to choose

reference answer

GIF:

  1. 8-bit pixels, 256 colors

  2. compression lossless

  3. Support for simple animations

  4. Support for boolean transparency

  5. Suitable for simple animation

JPEG

  1. Color limited to 256

  2. compression loss (in digital technology)

  3. Controllable compression quality

  4. Does not support transparency

  5. Suitable for photos

PNG

  1. Available in PNG8 and truecolor PNG.

  2. PNG8 is similar to GIF with 256 color limit, small file size, alpha transparency support, no animation.

  3. Suitable for icons, backgrounds, buttons

9、Display,float,position relationship

reference answer
  1. in the event thatdisplayis none, then neither position nor float work, in which case the element doesn't generate a frame.

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

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

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

  5. In all other cases, the value of display is the specified value, in summary:Absolute positioning, floats, and root elements all require adjustments to the display

10, how to center an element horizontally

reference answer
  • If the element to be centered isThe inline element in a regular stream, which sets the parent element'stext-align: center;can be realized

  • If the element to be centered isBlock Elements in Regular StreamsThe following are some examples of the margin settings: 1) set the width of the element, 2) set the left and right margins to auto, and 3) set the margins on the parent element under IE6.text-align: center;, and then restore the desired value to the child element

    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 isfloating element, 1) set the width for the element, 2)position: relative;3) the offset of the float direction (left or right) is set to 50%, and 4) the margin on the float direction is set to half the width of the element 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.         left50%;            /* 3 */
    15.         margin-left: -250px;  /* 4 */
    16.         background-color: purple;
    17.     }
    18. </style>
  • If the element to be centered isabsolute 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 width of the element times -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.         width800px;
    13.         position: absolute;
    14.         left50%;
    15.         margin-left: -400px;
    16.         background-color: purple;
    17.     }
    18. </style>
  • If the element to be centered isabsolute positioning element, 1) set the width of the element, 2) set both the left and right offsets to 0, 3) set both 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.         width800px;
    13.         position: absolute;
    14.         margin0 auto;
    15.         left0;
    16.         right0;
    17.         background-color: purple;
    18.     }
    19. </style>

JavaScript

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

reference answer

Seven data types

  • Boolean

  • Null

  • Undefined

  • Number

  • String

  • Symbol (new definition in ECMAScript 6)

  • Object

(Pre-ES6) 5 of which are basic types.string,number,boolean,null,undefined,

ES6 is out.Symbolis also a primitive data type that represents a unique value

Objectfor reference types (the range is quite large), also includes arrays, functions.

2. Is the Promise constructor executed synchronously or asynchronously, and what about the then method?

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

The output is:

  1. 1
  2. 2
  3. 4
  4. 3
  5. The promise constructor is executed synchronously.thenmethod is executed asynchronously
  6. Promise new immediately executes the code in it.thenis a microtask that will be executed when the current task is finished setTimeout is a macro task that will be executed when the next task is executed

3, JS's four design patterns

reference answer

factory model

The simple factory pattern can be understood as solving multiple similar problems; the

  1. function CreatePerson(name,age,sex) {
  2.     var obj = new Object();
  3.      = name;
  4.      = age;
  5.      = sex;
  6.      = 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. (p1.name); // longen
  14. (p1.age);  // 28
  15. (p1.sex);  // male
  16. (p1.sayName()); // longen
  17. (p2.name);  // tugenhua
  18. (p2.age);   // 27
  19. (p2.sex);   // women
  20. (p2.sayName()); // tugenhua  

singleton model

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

  1. // monomer mode
  2. var Singleton = function(name){
  3.      = name;
  4. };
  5. Singleton.prototype.getName = function(){
  6.     return ;
  7. }
  8. // Getting Instance Objects
  9. var getInstance = (function() {
  10.     var instance = null;
  11.     return function(name) {
  12.         if(!instance) {//Equivalent to a disposable valve, which can only be instantiated once.
  13.             instance = new Singleton(name);
  14.         }
  15.         return instance;
  16.     }
  17. })();
  18. // Tests for instances of the monadic model, so a===b
  19. var a = getInstance("aa");
  20. var b = getInstance("bb");  

sandbox mode

Put some functions into the self-executing function, but use closures to expose the interface, use variables to receive the exposed interface, and then call the value inside, otherwise you can't use the value inside.

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

Publisher Subscription Model

For example, if we follow a public number, and then he corresponds to a new message will be pushed to you.

  1. //Publisher and subscription models
  2.     var shoeObj = {}; // Define Publisher
  3.      = []; // Cache List Stores Subscriber Callback Functions
  4.     // Add Subscribers
  5.      = function(fn) {
  6.         (fn); // Subscription messages added to the cache list
  7.     }
  8.     // post a message
  9.      = function() {
  10.             for (var i = 0, fn; fn = [i++];) {
  11.                 (this, arguments);//The first argument just changes this of fn.
  12.             }
  13.         }
  14.      // Red subscribes to the following newsletter
  15.     (function(color, size) {
  16.         ("The color is:" + color);
  17.         ("The size is:" + size);
  18.     });
  19.     // Little Flower subscribes to the following news
  20.     (function(color, size) {
  21.         ("Once again the print color is:" + color);
  22.         ("Once again the print size is:" + size);
  23.     });
  24.     ("Red."40);
  25.     ("Black."42);  

The code implementation logic is to store subscribers in an array, the publisher callback function notifies by traversing the subscriber array and passing the publisher content into the subscriber array.

4. List the methods for centralized creation of instances

reference answer

1. Literal quantity

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

Constructor Creation

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

3. Using the factory pattern to create objects

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

4. Using the constructor to create objects

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

5. Briefly describe the front-end event flow

reference answer

HTML and javascript interaction is through the event-driven to achieve, such as mouse click event onclick, page scrolling event onscroll, etc., you can add event listeners to the document or document elements to book events. Want to know when these events are called, you need to understand the concept of "event flow".

What is event flow: event flow describes the sequence of events received from the page, DOM2 level event flow includes the following stages.

  • event capture phase

  • At target stage

  • event bubbling stage

addEventListeneraddEventListeneris a new DOM2 level event operation that specifies an event handler. This method takes three arguments: the name of the event to be handled, the function to be used as the event handler, and a boolean value. If this last boolean parameter is true, it means that the event handler is called in the capture phase; if it is false, it means that the event handler is called in the bubbling phase.

IE only supports event bubbling

6、What is Function._proto_(getPrototypeOf)?

reference answer

Get the prototype of an object, either in the form of __proto___ in chrome, or in the form of ES6.

So what is it? That is to say, what object Function is inherited from, let's do the following to determine.

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

We find that the prototype of Function is also Function.

We can make this relationship clear by using a diagram:

图片

7. Briefly describe the prototype / constructor / instance

reference answer
  • original form(prototype): A simple object that implements the object'sProperty inheritance. It can be simply understood as the object's dad. In Firefox and Chrome, eachJavaScriptobjects all contain a__proto__(non-standard) attributes pointing to its dad (the object's prototype) can beobj.__proto__Make a visit.

  • Constructor: can be accessed via thenewnextCreate a new objectThe function of the

  • Example: The constructor and thenewThe object created is the instance.Instances point to prototypes via __proto___ and constructors via constructor

Here's a chestnut toObjectAs an example, we commonly use theObjectis a constructor, so we can build instances from it.

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

Then, at this point, theThe instance is instanceThe constructor is Object, we know that the constructor has aprototypeproperty points to the prototype, so the prototype is.

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

Here we can see the relationship between the three.

  1. Instance. __proto__=== original form
  2. prototype.constructor=== constructor
  3. Constructor.prototype === original form
  4. // This line is actually fetched based on the prototype, and can be understood as a mapping line based on the prototype
  5. // Example.
  6. // const o = new Object()
  7. //  === Object   --> true
  8. // o.__proto__ = null;
  9. //  === Object   --> false
  10. instance.constructor=== constructor

8, a brief description of the JS inheritance, and examples

reference answer

In JS, inheritance is usually referred to asPrototype Chain Inheritance, that is, by specifying a prototype and being able to inherit properties or methods from the prototype through a prototype chain.

  • Optimization.Grail pattern

    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. })();
  • Using ES6 Syntactic Sugarclass / extends

9、Function Collierization

reference answer

In functional programming, functions are first-class citizens. So how does function Collierization work?

Function Colliarization refers to the technique of converting a function that can take multiple arguments into a function that takes a single argument and returns a new function that takes the remaining arguments and returns a result.

The main roles and features of function currying are parameter reuse, early return and delayed execution.

The technique of populating a function with a few arguments and then returning a new function is called the Collierization of a function. It can often be used to kirigize a function without intruding into the function'sPreset General Parameters, for multiple re-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. What is the difference between bind, call and apply?

reference answer

call cap (a poem)apply It's all about fixing change.this The pointers are the same. The roles are the same, just the way the parameter is passed is different.

In addition to the first argument, thecall can take a list of arguments.apply Accepts only an array of parameters.

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

bindand the other two methods work the same way, except that the method returns a function. And we can pass thebindAchieving Curryization.

(The following is an extended description of these three methods)

How to implement a bind function

There are several ways to think about implementing the following functions

  • is not passed in as the first parameter, then it defaults towindow

  • Changing the pointing to this allows the new object to execute the function. So could the idea be to add a function to the new object and then remove 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.   // Return a function
  8.   return function F() {
  9.     // Since it returns a function, we can new F(), so we need to determine
  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.   // Add a property to context
  4.   // getValue.call(a, 'yck''24'=>  = getValue
  5.    = this
  6.   // Take out the parameter after context
  7.   var args = [...arguments].slice(1)
  8.   // getValue.call(a, 'yck''24'=> ('yck''24')
  9.   var result = (...args)
  10.   // Delete fn
  11.   delete 
  12.   return result
  13. }

How to implement an apply function

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

11, the characteristics of the arrow function

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

Arrow functions are actually notthisof this function, thethisdepends only on the first function outside of him that is not an arrow function'sthis. In this example, because the call toamatches the first case in the previous code, sothisbewindow. And.thisOnce the context is bound, 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 cap (a poem)undefined

  • B: Lydia cap (a poem)ReferenceError

  • C: ReferenceError cap (a poem)21

  • D: undefined cap (a poem)ReferenceError

reference answer

In the function, we first use thevarThe keyword declares thenameVariables. This means that variables are promoted during the creation phase (JavaScriptwill allocate memory space for the created variable during its creation phase), with a default value ofundefined, until we actually execute to the line that uses the variable. We haven't created a new line for thenamevariable assignment, so it still maintains theundefinedThe value of the

utilizationletKeywords (andconst) declared variables will also have variable lifting, but unlike thevarUnlike the initialization, the 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, theJavaScriptwill throw aReferenceError

with respect toletof whether there is variable lifting, how can we verify this with the following example:

  1. let name = 'ConardLi'
  2. {
  3.   (name) // Uncaught ReferenceError: name is not defined
  4.   let name = 'code secret garden'
  5. }

letvariable if there is no variable lifting.(name)will then outputConardLi, and the result throws up theReferenceErrorWell that's a good indication.letThere is also variable lifting, but it has a "temporary dead zone" that does not allow access until the variable is initialized or assigned a value.

The assignment of variables can be divided into three stages:

  • Creating variables to open up space in memory

  • Initialize the variable toundefined

  • Real Assignment

with respect toletvarcap (a poem)function

  • let's 'creation' process is boosted, but initialization is not.

  • var's 'Create' and 'Initialize' are boosted.

  • functionThe "Create" "Initialize" and "Assign" have been elevated.

2. What is the output of the following code

  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 order: undefined -> 10 -> 20

  1. In an immediately executable function, var a= 20The ; statement defines a local variable a. Because of js's variable declaration elevation mechanism, the declaration of local variable a is elevated to the top of the body of the function that executes it immediately, and because this elevation does not include an assignment, the first print statement prints undefined, and the last print statement prints20
  2. Due to variable declaration lifting, a= 5At the time this statement is executed, the local variable a has already been declared, so it has the effect of assigning a value to the local variable a, which is still the same as the first assignment.10

3. What is the output of the following?

  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

colorChangeMethods are static. Static methods exist only in the constructor that creates them and cannot be passed to any child level. Since thefreddieis a sublevel object that the function does not pass, so it is not necessary to pass it in thefreddieNot available on the instancefreddieMethod: ThrowTypeError

4. When will the following code output 1?

  1. var a = ?;
  2. if(a == 1 && a == 2 && a == 3){
  3.      (1);
  4. }
  5. reference answer

Since == does an implicit type conversion, we'll just override the toString method.

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

5. What is the output of the following?

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

1. Using the first push, the push method of the obj object is set toobj[2]=1;+=12. Using the second push, the push method of the obj object is set toobj[3]=2;+=13. When using the output, because obj has the length property and the splice method, it will be printed as an array. 4. When printing, because the array is not set to the value of the subscript at 0 1, it will be printed as empty, and the active obj[0] will be undefined.

图片

6. What is the output of the following code?

  1. var a = {n: 1};
  2. var b = a;
  3.  = a = {n: 2};
  4. ()     
  5. ()
  6. reference answer

undefined {n:2}

First, both a and b refer to the {n:2} object, and then execution proceeds to the = a = {n:2} statement, and while it is true that assignment is right-to-left, . has a higher priority than =, so it is executed first here, which is equivalent to adding a new attribute x to the {n:1} object pointed to by a (or b), i.e., at this point the object will become {n:1;x:undefined}. After that, the assignments are made from right to left as normal. When a = {n:2} is executed, the reference to a changes to point to the new object {n:2}, while b still points to the old object. Later, when a = {n:2} is executed, a is not parsed again, but the original a is parsed, i.e., the old object, so the value of x in the old object is {n:2}, and the old object is {n:1;x:{n:2}}, which is referenced by b. The latter output, again to resolve a, at this time the a is pointing to the new object of a, and this new object is no x attribute, so access to the output undefined; and access to the old object will output the value of x, that is, {n:2}.

7. What is the output of the following code?

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

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

In comparing equivalence, primitive types are compared by their values, while objects are compared by their references.JavaScriptChecks if the object has a reference to the same location in memory.

The object we pass as a parameter and the object we use to check for equality are located in different places in memory, so their references are different.

That's why.{ age: 18 } === { age: 18 }cap (a poem){ age: 18 } == { age: 18 }come (or go) backfalseThe reason.

8. What is the output of the following code?

  1. const obj = { 1"a"2"b"3"c" };
  2. const set = new Set([12345]);
  3. ("1");
  4. (1);
  5. set.has("1");
  6. set.has(1);
  7. reference answer
true` `true` `false` `true

All object keys (excludingSymbols) are stored as strings, even if you don't have a key of the given string type. This is why the('1')also returnstrue

The above statement does not apply toSet. In ourSetnot included“1”('1')come (or go) backfalse. It has numeric types1(1)come (or go) backtrue

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. (a[b]);
  6. ---------------------
  7. // example 2
  8. var a={}, b=Symbol('123'), c=Symbol('123');  
  9. a[b]='b';
  10. a[c]='c';  
  11. (a[b]);
  12. ---------------------
  13. // example 3
  14. var a={}, b={key:'123'}, c={key:'456'};  
  15. a[b]='b';
  16. a[c]='c';  
  17. (a[b]);
  18. reference answer

This question examines the conversion of the key name of an object.

  • The key name of an object can only be of type String and Symbol.

  • Key names of other types are converted to string types.

  • The toString method is called by default to convert an object to a string.

  1. // example 1
  2. var a={}, b='123', c=123;
  3. a[b]='b';
  4. // The key name of c is converted to a string.'123'This overwrites b.
  5. a[c]='c';  
  6. // Output c
  7. (a[b]);
  8. // example 2
  9. var a={}, b=Symbol('123'), c=Symbol('123');  
  10. // b is of type Symbol and does not need to be converted.
  11. a[b]='b';
  12. // c is of type Symbol and does not need to be converted. The values of any of the Symbol types are not equal, so they don't override b.
  13. a[c]='c';
  14. // Output b
  15. (a[b]);
  16. // example 3
  17. var a={}, b={key:'123'}, c={key:'456'};  
  18. // b is not a string or a Symbol type and needs to be converted to a string.
  19. // The object type is converted to a string by calling the toString method [object Object]。
  20. a[b]='b';
  21. // c is not a string nor a Symbol type, it needs to be converted to a string.
  22. // The object type is converted to a string by calling the toString method [object Object]. Here b will be overwritten.
  23. a[c]='c';  
  24. // Output c
  25. (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. })();
  12. reference answer
1` `undefined` `2

catchBlock Receiving Parametersx. When we pass a parameter, this is the same as the variablexdifferent. This variablexbelongcatchScoped.

After that, we set the variables of this block-level scope to1and set the variablesyvalues. Now, we print the block-scoped variablexIt is equal to1

existcatchBeyond the block.xremainundefinedbut (not)ybe2. When we want to be incatchOutside of the block(x)When it returnsundefinedbut (not)ycome (or go) back2

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();
  19. reference answer

The output sequence is 4 2 1

  1. function Foo() {
  2.      = function() {
  3.         (1)
  4.     }
  5.      = function() {
  6.         (2)
  7.     }
  8. }
  9. // The above is just a build method for Foo, no instance is created and no execution is done at this moment.
  10. Foo.prototype.a = function() {
  11.     (3)
  12. }
  13. // Now the prototype method a is mounted on Foo, and the method output value is3
  14.  = function() {
  15.     (4)
  16. }
  17. // Now the direct method a is mounted on Foo and the output value is4
  18. Foo.a();
  19. // immediately executes the a method on Foo, which was just defined, so the
  20. // # Output4
  21. let obj = new Foo();
  22. /* Foo's build method is called here, and it does two main things:
  23. 1. Replace the direct method a on the global Foo with an output1 The methodology.
  24. 2. Mount the direct method a on the new object and the output value is2
  25. */
  26. obj.a();
  27. // Because there is a direct method a, there is no need to access the prototype chain, so it uses the constructor method defined in .
  28. // # Output2
  29. Foo.a();
  30. // The a method on the global Foo has been replaced in the build method, so the
  31. // # Output1