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
-
function debounce(fn) {
-
let timeout = null; // Create a tag to hold the timer's return value
-
return function () {
-
clearTimeout(timeout); // Clear the previous setTimeout every time the user enters it
-
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
-
fn.apply(this, arguments);
-
}, 500);
-
};
-
}
-
function sayHi() {
-
console.log('Anti-shake successful');
-
}
-
-
var inp = document.getElementById('inp');
-
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.
-
function throttle(fn) {
-
let canRun = true; // Saving a token through a closure
-
return function () {
-
if (!canRun) return; // Determine at the beginning of the function if the marker istruenot fortrueimitatereturn
-
canRun = false; // Immediately set tofalse
-
setTimeout(() => { // Place the execution of externally passed functions in setTimeout
-
(this, arguments);
-
// 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)
-
canRun = true;
-
}, 500);
-
};
-
}
-
function sayHi(e) {
-
(, );
-
}
-
('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。
-
(function(){
-
return {
-
data:[]
-
}
-
})()
AMD: Use requireJS to write modular, features:Dependencies must be declared well in advance。
-
define('./',function(code){
-
// code just likeindex.js Returns
-
})
CMD: Use seaJS to write modularity, features:Support for dynamic introduction of dependency files。
-
define(function(require, exports, module) {
-
var indexCode = require('./');
-
})
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 install
command -
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
.npm
directory -
Extract the zip to the current project's
node_modules
catalogs -
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):
-
Execute the project itself preinstall
The preinstall hook will be executed if it is defined in the current npm project.
-
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.
-
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.
-
-
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
-
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).
-
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.
-
function test(){
-
var aa = 0;
-
var testSet = setInterval(function(){
-
aa++;
-
(123);
-
if(aa<10){
-
clearInterval(testSet);
-
}
-
},20);
-
var testSet1 = setTimeout(function(){
-
(321)
-
},1000);
-
for(var i=0;i<10;i++){
-
('test');
-
}
-
}
-
test()
Output results:
-
test //10substandard
-
undefined
-
123
-
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
-
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
-
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
-
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.
-
function test () {
-
('start')
-
setTimeout(() => {
-
('children2')
-
().then(() => {('children2-1')})
-
}, 0)
-
setTimeout(() => {
-
('children3')
-
().then(() => {('children3-1')})
-
}, 0)
-
().then(() => {('children1')})
-
('end')
-
}
-
-
test()
-
-
// The above code in the node11Execution results for the following version (all macrotasks are executed first, then microtasks)
-
// start
-
// end
-
// children1
-
// children2
-
// children3
-
// children2-1
-
// children3-1
-
-
// The above code in the node11and browser execution results (sequential execution of macrotasks and microtasks)
-
// start
-
// end
-
// children1
-
// children2
-
// children2-1
-
// children3
-
// 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:
-
The server sends the public key to the client.
-
The attacker intercepts the public key and keeps it for himself.
-
The attacker then generates a [forged] public key himself and sends it to the client.
-
The client receives the forged public key and generates an encrypted hash value to send to the server.
-
The attacker gets the encrypted hash value and decrypts it with his own private key to get the true secret key.
-
A fake encrypted hash value is also generated and sent to the server.
-
The server decrypts the private key to obtain the fake secret key.
-
The server transmits the information encrypted with an encrypted key
Precautionary approach:
-
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 the
color
It'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.
-
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.
-
Then determine whether the
resize
orscroll
If it does, it will go and trigger the event, soresize
cap (a poem)scroll
The event is also triggered at least once every 16ms and comes with a throttling feature. -
Determines if a media query has been triggered
-
Update animation and send events
-
Determine if there is a full-screen action event
-
fulfillment
requestAnimationFrame
pull back (of a key (in music) -
fulfillment
IntersectionObserver
callback, this method is used to determine whether an element is visible or not, can be used on lazy loading, but compatibility is not good -
Updating the interface
-
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 the
requestIdleCallback
Callback.
Reduce redraws and reflows
-
utilization
translate
substitute fortop
-
<div class="test"></div>
-
<style>
-
.test {
-
position: absolute;
-
top: 10px;
-
width: 100px;
-
height: 100px;
-
background: red;
-
}
-
</style>
-
<script>
-
setTimeout(() => {
-
// cause reflux
-
('.test').style.top = '100px'
-
}, 1000)
-
</script>
-
-
utilization
visibility
interchangeabilitydisplay: 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 the
display:none
(with one Reflow) and then you modify it 100 times and then show it againDon't put DOM node attribute values in a loop as variables in the loop.
-
for(let i = 0; i < 1000; i++) {
-
// Getting the offsetTop will cause a reflow because you need to get the correct value.
-
(('.test').)
-
}
-
-
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 the
requestAnimationFrame
-
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 the
video
tag, 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-reference
When 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:
-
// vue project src/core/vdom/ -488classifier for objects in rows such as words
-
// Here is the code formatted for readability
-
-
// oldCh is an array of old virtual nodes
-
if (isUndef(oldKeyToIdx)) {
-
oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
-
}
-
if(isDef(newStartVnode.key)) {
-
// map
-
idxInOld = oldKeyToIdx[newStartVnode.key]
-
} else {
-
// Iteration to get
-
idxInOld = findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)
-
}
Creating a map function
-
function createKeyToOldIdx (children, beginIdx, endIdx) {
-
let i, key
-
const map = {}
-
for (i = beginIdx; i <= endIdx; ++i) {
-
key = children[i].key
-
if (isDef(key)) map[key] = i
-
}
-
return map
-
}
Iterative search
-
// sameVnode is a function that compares old and new nodes to see if they are the same.
-
function findIdxInOld (node, oldCh, start, end) {
-
for (let i = start; i < end; i++) {
-
const c = oldCh[i]
-
-
if (isDef(c) && sameVnode(node, c)) return i
-
}
-
}
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
-
class Example extends React.Component {
-
constructor() {
-
super();
-
this.state = {
-
val: 0
-
};
-
}
-
-
componentDidMount() {
-
this.setState({val: this.state.val + 1});
-
(this.state.val); // 1st log
-
-
this.setState({val: this.state.val + 1});
-
(this.state.val); // 2nd log
-
-
setTimeout(() => {
-
this.setState({val: this.state.val + 1});
-
(this.state.val); // 3rd log
-
-
this.setState({val: this.state.val + 1});
-
(this.state.val); // 4th log
-
}, 0);
-
}
-
-
render() {
-
return null;
-
}
-
};
-
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。
-
-
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。
-
-
3The code in the setTimeout isBatchingUpdates when triggered.falseSo the update can be done directly, so the output is linked to the2,3。
-
-
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.clearfix
, clear:both
,overflow:hidden
;
Better yet..clearfix
Pseudo-elemental jack-of-all-trades versions, the latter two having limitations.
-
.clearfix:after {
-
visibility: hidden;
-
display: block;
-
font-size: 0;
-
content: " ";
-
clear: both;
-
height: 0;
-
}
-
-
<!--
-
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.
-
.clearfix There's another way to write it.
-
-->
-
-
.clearfix:before, .clearfix:after {
-
content:"";
-
display:table;
-
}
-
.clearfix:after{
-
clear:both;
-
overflow:hidden;
-
}
-
.clearfix{
-
zoom:1;
-
}
-
-
<!--
-
expense or outlaydisplay:table is to avoid margin collapse caused by overlapping margins.
-
Internal elements become table-cells by default.
-
-->
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:hidden
This can be formed if used in the same container.BFC
Avoid 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:
-
Reduces the number of HTTP requests and dramatically improves page load speeds
-
Increase image information repetition, improve compression ratio, reduce image size
-
Easy to change the style, just change the color or style on one or several pictures to achieve
Drawbacks:
-
Trouble merging images
-
Maintenance hassles, modifying an image may require re-layout of the entire image, style
5、link
together with@import
exclusionary rule
reference answer
-
link
is in HTML.@import
It's the CSS way. -
link
Maximum support for parallel downloads.@import
Too much nesting leads to serial downloads and FOUCs -
link
This can be done byrel="alternate stylesheet"
Specify Candidate Style -
browser's view of
link
Supported earlier than@import
You can use the@import
Hide styles for older browsers -
@import
It is possible to refer to other files in the css file before the style rule -
Overall:link is superior to @import
6、display: block;
cap (a poem)display: inline;
exclusionary rule
reference answer
block
Elemental Characteristics:
1. When in regular flow, if thewidth
No 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
inline
Elemental Characteristics
1. Horizontally according todirection
arrange in order
2. Will not do line breaks before and after the element
3. Subject towhite-space
containment
4.margin/padding
Invalid in the vertical direction, valid in the horizontal direction
5.width/height
attribute 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-height
determines that the line box height of the replacement in-line element is determined by theheight
,margin
,padding
,border
Decision 7. Float or absolute positioning will be converted toblock
8.vertical-align
Attributes take effect
7, the container contains a number of floating elements when how to clean up the float
reference answer
-
Adds an extra element before the container element closure tag and sets the
clear: both
-
The parent element triggers the block-level formatting context (see the section on block-level visualization contexts)
-
Setting up container elements pseudo-elements for cleanup Recommended methods for cleaning up floats
-
/**
-
* Use in standard browsers
-
* 1 contentThe content of the space is used to fix a document under opera that has a
-
* The contenteditable attribute clears up whitespace above and below a floating element.
-
* 2 utilizationdisplayutilizationtablerather thanblock: It is possible to prevent the container and
-
* The child element top-margin collapses, which makes the cleanup effect the same as BFC, IE6/7
-
* zoom: 1; Consistency
-
**/
-
-
.clearfix:before,
-
.clearfix:after {
-
content: " "; /* 1 */
-
display: table; /* 2 */
-
}
-
-
.clearfix:after {
-
clear: both;
-
}
-
-
/**
-
* IE 6/7under the jurisdiction of
-
* Include floats by triggering hasLayout
-
**/
-
.clearfix {
-
*zoom: 1;
-
}
8、PNG,GIF,JPG difference and how to choose
reference answer
GIF:
-
8-bit pixels, 256 colors
-
compression lossless
-
Support for simple animations
-
Support for boolean transparency
-
Suitable for simple animation
JPEG:
-
Color limited to 256
-
compression loss (in digital technology)
-
Controllable compression quality
-
Does not support transparency
-
Suitable for photos
PNG:
-
Available in PNG8 and truecolor PNG.
-
PNG8 is similar to GIF with 256 color limit, small file size, alpha transparency support, no animation.
-
Suitable for icons, backgrounds, buttons
9、Display,float,position relationship
reference answer
-
in the event that
display
is none, then neither position nor float work, in which case the element doesn't generate a frame. -
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.
-
Otherwise, if float is not none, the box is floated and the display is adjusted according to the following table
-
Otherwise, if the element is the root element, the display is adjusted according to the following table
-
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's
text-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 -
-
<body>
-
<div class="content">
-
aaaaaa aaaaaa a a a a a a a a
-
</div>
-
</body>
-
-
<style>
-
body {
-
background: #DDD;
-
text-align: center; /* 3 */
-
}
-
.content {
-
width: 500px; /* 1 */
-
text-align: left; /* 3 */
-
margin: 0 auto; /* 2 */
-
-
background: purple;
-
}
-
</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.-
<body>
-
<div class="content">
-
aaaaaa aaaaaa a a a a a a a a
-
</div>
-
</body>
-
-
<style>
-
body {
-
background: #DDD;
-
}
-
.content {
-
width: 500px; /* 1 */
-
float: left;
-
-
position: relative; /* 2 */
-
left: 50%; /* 3 */
-
margin-left: -250px; /* 4 */
-
-
background-color: purple;
-
}
-
</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
-
<body>
-
<div class="content">
-
aaaaaa aaaaaa a a a a a a a a
-
</div>
-
</body>
-
-
<style>
-
body {
-
background: #DDD;
-
position: relative;
-
}
-
.content {
-
width: 800px;
-
-
position: absolute;
-
left: 50%;
-
margin-left: -400px;
-
-
background-color: purple;
-
}
-
</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
-
<body>
-
<div class="content">
-
aaaaaa aaaaaa a a a a a a a a
-
</div>
-
</body>
-
-
<style>
-
body {
-
background: #DDD;
-
position: relative;
-
}
-
.content {
-
width: 800px;
-
-
position: absolute;
-
margin: 0 auto;
-
left: 0;
-
right: 0;
-
-
background-color: purple;
-
}
-
</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.Symbol
is also a primitive data type that represents a unique value
Object
for 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?
-
reference answer
-
const promise = new Promise((resolve, reject) => {
-
console.log(1)
-
resolve()
-
console.log(2)
-
})
-
-
promise.then(() => {
-
console.log(3)
-
})
-
-
console.log(4)
The output is:
-
1
-
2
-
4
-
3
-
The promise constructor is executed synchronously.thenmethod is executed asynchronously
-
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
-
function CreatePerson(name,age,sex) {
-
var obj = new Object();
-
= name;
-
= age;
-
= sex;
-
= function(){
-
return ;
-
}
-
return obj;
-
}
-
var p1 = new CreatePerson("longen",'28','Male');
-
var p2 = new CreatePerson("tugenhua",'27','Female');
-
(p1.name); // longen
-
(p1.age); // 28
-
(p1.sex); // male
-
(p1.sayName()); // longen
-
-
(p2.name); // tugenhua
-
(p2.age); // 27
-
(p2.sex); // women
-
(p2.sayName()); // tugenhua
singleton model
Can only be instantiated (constructor adds properties and methods to the instance) once
-
// monomer mode
-
var Singleton = function(name){
-
= name;
-
};
-
Singleton.prototype.getName = function(){
-
return ;
-
}
-
// Getting Instance Objects
-
var getInstance = (function() {
-
var instance = null;
-
return function(name) {
-
if(!instance) {//Equivalent to a disposable valve, which can only be instantiated once.
-
instance = new Singleton(name);
-
}
-
return instance;
-
}
-
})();
-
// Tests for instances of the monadic model, so a===b
-
var a = getInstance("aa");
-
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.
-
let sandboxModel=(function(){
-
function sayName(){};
-
function sayAge(){};
-
return{
-
sayName:sayName,
-
sayAge:sayAge
-
}
-
})()
Publisher Subscription Model
For example, if we follow a public number, and then he corresponds to a new message will be pushed to you.
-
//Publisher and subscription models
-
var shoeObj = {}; // Define Publisher
-
= []; // Cache List Stores Subscriber Callback Functions
-
-
// Add Subscribers
-
= function(fn) {
-
(fn); // Subscription messages added to the cache list
-
}
-
-
// post a message
-
= function() {
-
for (var i = 0, fn; fn = [i++];) {
-
(this, arguments);//The first argument just changes this of fn.
-
}
-
}
-
// Red subscribes to the following newsletter
-
(function(color, size) {
-
("The color is:" + color);
-
("The size is:" + size);
-
});
-
-
// Little Flower subscribes to the following news
-
(function(color, size) {
-
("Once again the print color is:" + color);
-
("Once again the print size is:" + size);
-
});
-
("Red.", 40);
-
("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
-
let Obj=new Object()
-
Obj.name='Zhang San'
3. Using the factory pattern to create objects
-
function createPerson(name){
-
var o = new Object();
-
o.name = name;
-
};
-
return o;
-
}
-
var person1 = createPerson('Zhang San');
4. Using the constructor to create objects
-
function Person(name){
-
this.name = name;
-
}
-
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
addEventListener:addEventListeneris 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.
-
Function.__proto__==Object.prototype //false
-
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, eachJavaScript
objects 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 the
new
nextCreate a new objectThe function of the -
Example: The constructor and the
new
The object created is the instance.Instances point to prototypes via __proto___ and constructors via constructor。
Here's a chestnut toObject
As an example, we commonly use theObject
is a constructor, so we can build instances from it.
-
// Example
-
const instance = new Object()
Then, at this point, theThe instance is instance, The constructor is Object, we know that the constructor has aprototype
property points to the prototype, so the prototype is.
-
// original form
-
const prototype = Object.prototype
Here we can see the relationship between the three.
-
Instance. __proto__=== original form
-
-
prototype.constructor=== constructor
-
-
Constructor.prototype === original form
-
-
// This line is actually fetched based on the prototype, and can be understood as a mapping line based on the prototype
-
// Example.
-
// const o = new Object()
-
// === Object --> true
-
// o.__proto__ = null;
-
// === Object --> false
-
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
-
var inherit = (function(c,p){
-
var F = function(){};
-
return function(c,p){
-
F.prototype = p.prototype;
-
c.prototype = new F();
-
c.uber = p.prototype;
-
c.prototype.constructor = c;
-
}
-
})();
-
-
Using ES6 Syntactic Sugar
class / 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.
-
const add = function add(x) {
-
return function (y) {
-
return x + y
-
}
-
}
-
-
const add1 = add(1)
-
-
add1(2) === 3
-
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.
-
let a = {
-
value: 1
-
}
-
function getValue(name, age) {
-
console.log(name)
-
console.log(age)
-
console.log(this.value)
-
}
-
getValue.call(a, 'yck', '24')
-
getValue.apply(a, ['yck', '24'])
bind
and the other two methods work the same way, except that the method returns a function. And we can pass thebind
Achieving 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 to
window
-
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?
-
Function.prototype.myBind = function (context) {
-
if (typeof this !== 'function') {
-
throw new TypeError('Error')
-
}
-
var _this = this
-
var args = [...arguments].slice(1)
-
// Return a function
-
return function F() {
-
// Since it returns a function, we can new F(), so we need to determine
-
if (this instanceof F) {
-
return new _this(...args, ...arguments)
-
}
-
return _this.apply(context, args.concat(...arguments))
-
}
-
}
How to implement a call function
-
Function.prototype.myCall = function (context) {
-
var context = context || window
-
// Add a property to context
-
// getValue.call(a, 'yck', '24') => = getValue
-
= this
-
// Take out the parameter after context
-
var args = [...arguments].slice(1)
-
// getValue.call(a, 'yck', '24') => ('yck', '24')
-
var result = (...args)
-
// Delete fn
-
delete
-
return result
-
}
How to implement an apply function
-
Function.prototype.myApply = function (context) {
-
var context = context || window
-
= this
-
-
var result
-
// Need to determine whether to store the second parameter
-
// If present, expand the second argument
-
if (arguments[1]) {
-
result = (...arguments[1])
-
} else {
-
result = ()
-
}
-
-
delete
-
return result
-
}
11, the characteristics of the arrow function
-
reference answer
-
function a() {
-
return () => {
-
return () => {
-
console.log(this)
-
}
-
}
-
}
-
console.log(a()()())
Arrow functions are actually notthis
of this function, thethis
depends only on the first function outside of him that is not an arrow function'sthis
. In this example, because the call toa
matches the first case in the previous code, sothis
bewindow
. And.this
Once the context is bound, it will not be changed by any code.
Program reading questions
1. What is the output of the following program?
-
function sayHi() {
-
console.log(name);
-
console.log(age);
-
var name = "Lydia";
-
let age = 21;
-
}
-
-
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 thevar
The keyword declares thename
Variables. This means that variables are promoted during the creation phase (JavaScript
will 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 thename
variable assignment, so it still maintains theundefined
The value of the
utilizationlet
Keywords (andconst
) declared variables will also have variable lifting, but unlike thevar
Unlike 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, theJavaScript
will throw aReferenceError
。
with respect tolet
of whether there is variable lifting, how can we verify this with the following example:
-
let name = 'ConardLi'
-
{
-
(name) // Uncaught ReferenceError: name is not defined
-
let name = 'code secret garden'
-
}
let
variable if there is no variable lifting.(name)
will then outputConardLi
, and the result throws up theReferenceError
Well that's a good indication.let
There 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 to
undefined
-
Real Assignment
with respect tolet
、var
cap (a poem)function
:
-
let
's 'creation' process is boosted, but initialization is not. -
var
's 'Create' and 'Initialize' are boosted. -
function
The "Create" "Initialize" and "Assign" have been elevated.
2. What is the output of the following code
-
var a = 10;
-
(function () {
-
console.log(a)
-
a = 5
-
console.log(window.a)
-
var a = 20;
-
console.log(a)
-
})()
Output in order: undefined -> 10 -> 20
-
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。
-
-
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?
-
class Chameleon {
-
static colorChange(newColor) {
-
this.newColor = newColor;
-
}
-
-
constructor({ newColor = "green" } = {}) {
-
this.newColor = newColor;
-
}
-
}
-
-
const freddie = new Chameleon({ newColor: "purple" });
-
freddie.colorChange("orange");
-
A:
orange
-
B:
purple
-
C:
green
-
D:
TypeError
Answer: D
colorChange
Methods are static. Static methods exist only in the constructor that creates them and cannot be passed to any child level. Since thefreddie
is a sublevel object that the function does not pass, so it is not necessary to pass it in thefreddie
Not available on the instancefreddie
Method: ThrowTypeError
。
4. When will the following code output 1?
-
var a = ?;
-
if(a == 1 && a == 2 && a == 3){
-
(1);
-
}
-
reference answer
Since == does an implicit type conversion, we'll just override the toString method.
-
var a = {
-
i: 1,
-
toString() {
-
return ++;
-
}
-
}
-
-
if( a == 1 && a == 2 && a == 3 ) {
-
(1);
-
}
5. What is the output of the following?
-
var obj = {
-
'2': 3,
-
'3': 4,
-
'length': 2,
-
'splice': Array.prototype.splice,
-
'push': Array.prototype.push
-
}
-
(1)
-
(2)
-
(obj)
-
reference answer
1. Using the first push, the push method of the obj object is set toobj[2]=1;+=1
2. Using the second push, the push method of the obj object is set toobj[3]=2;+=1
3. 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?
-
var a = {n: 1};
-
var b = a;
-
= a = {n: 2};
-
-
()
-
()
-
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?
-
function checkAge(data) {
-
if (data === { age: 18 }) {
-
("You are an adult!");
-
} else if (data == { age: 18 }) {
-
("You are still an adult.");
-
} else {
-
(`Hmm.. You don't have an age I guess`);
-
}
-
}
-
-
checkAge({ age: 18 });
-
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.JavaScript
Checks 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) backfalse
The reason.
8. What is the output of the following code?
-
const obj = { 1: "a", 2: "b", 3: "c" };
-
const set = new Set([1, 2, 3, 4, 5]);
-
-
("1");
-
(1);
-
set.has("1");
-
set.has(1);
-
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 ourSet
not 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?
-
// example 1
-
var a={}, b='123', c=123;
-
a[b]='b';
-
a[c]='c';
-
(a[b]);
-
-
---------------------
-
// example 2
-
var a={}, b=Symbol('123'), c=Symbol('123');
-
a[b]='b';
-
a[c]='c';
-
(a[b]);
-
-
---------------------
-
// example 3
-
var a={}, b={key:'123'}, c={key:'456'};
-
a[b]='b';
-
a[c]='c';
-
(a[b]);
-
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.
-
// example 1
-
var a={}, b='123', c=123;
-
a[b]='b';
-
// The key name of c is converted to a string.'123'This overwrites b.
-
a[c]='c';
-
// Output c
-
(a[b]);
-
-
-
// example 2
-
var a={}, b=Symbol('123'), c=Symbol('123');
-
// b is of type Symbol and does not need to be converted.
-
a[b]='b';
-
// 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.
-
a[c]='c';
-
// Output b
-
(a[b]);
-
-
-
// example 3
-
var a={}, b={key:'123'}, c={key:'456'};
-
// b is not a string or a Symbol type and needs to be converted to a string.
-
// The object type is converted to a string by calling the toString method [object Object]。
-
a[b]='b';
-
// c is not a string nor a Symbol type, it needs to be converted to a string.
-
// The object type is converted to a string by calling the toString method [object Object]. Here b will be overwritten.
-
a[c]='c';
-
// Output c
-
(a[b]);
10. What is the output of the following code?
-
(() => {
-
let x, y;
-
try {
-
throw new Error();
-
} catch (x) {
-
(x = 1), (y = 2);
-
console.log(x);
-
}
-
console.log(x);
-
console.log(y);
-
})();
-
reference answer
1` `undefined` `2
catch
Block Receiving Parametersx
. When we pass a parameter, this is the same as the variablex
different. This variablex
belongcatch
Scoped.
After that, we set the variables of this block-level scope to1
and set the variablesy
values. Now, we print the block-scoped variablex
It is equal to1
。
existcatch
Beyond the block.x
remainundefined
but (not)y
be2
. When we want to be incatch
Outside of the block(x)
When it returnsundefined
but (not)y
come (or go) back2
。
11. What is the output of the following code?
-
function Foo() {
-
Foo.a = function() {
-
console.log(1)
-
}
-
this.a = function() {
-
console.log(2)
-
}
-
}
-
Foo.prototype.a = function() {
-
console.log(3)
-
}
-
Foo.a = function() {
-
console.log(4)
-
}
-
Foo.a();
-
let obj = new Foo();
-
obj.a();
-
Foo.a();
-
reference answer
The output sequence is 4 2 1
-
function Foo() {
-
= function() {
-
(1)
-
}
-
= function() {
-
(2)
-
}
-
}
-
// The above is just a build method for Foo, no instance is created and no execution is done at this moment.
-
-
Foo.prototype.a = function() {
-
(3)
-
}
-
// Now the prototype method a is mounted on Foo, and the method output value is3
-
-
= function() {
-
(4)
-
}
-
// Now the direct method a is mounted on Foo and the output value is4
-
-
Foo.a();
-
// immediately executes the a method on Foo, which was just defined, so the
-
// # Output4
-
-
let obj = new Foo();
-
/* Foo's build method is called here, and it does two main things:
-
1. Replace the direct method a on the global Foo with an output1 The methodology.
-
2. Mount the direct method a on the new object and the output value is2。
-
*/
-
-
obj.a();
-
// Because there is a direct method a, there is no need to access the prototype chain, so it uses the constructor method defined in .
-
// # Output2
-
-
Foo.a();
-
// The a method on the global Foo has been replaced in the build method, so the
-
// # Output1