Before Posting, xiaobian would like to first for the last article – CSS correction and optimization of the article proposed partners thank you, each of your suggestions or comments are very valuable 🌻🌻.

Following on from the previous two articles, HTML and CSS, this article gives you a rough integration of common Javascript sections. The scope of knowledge involved in the article is still very wide, xiaobian in the sorting time also by the way to review again.

The article is 15,000 words +, the length is relatively long, or suggest to collect it, slowly read. This article is a useful refresher (especially if you’re looking for a new job) πŸ₯΄.

PS: In the article, in order to facilitate reading, xiaobian as always made a dividing line.


1. How does this work in πŸ€ͺJavaScript

First, in JS, this refers to the “owner” of the execution and, more specifically, to the object that treats the current function as a method.

This in javascript has a mechanism for handling this that is not used in other languages at all. In each of the five cases, this refers to something different.

The global scope

When in global scope, using this will point to the global object (this->window);

Object method call

This is in the object. When a function is saved as a property of an object, the function is a method of that object and the value of this in the function is that object.

Let’s start with an example:

const object = {
    a: 1, 
    func: function() {
        console.log(this.a)
    }
}

object.func()  //1  (this->object)
Copy the code
function func() {
     console.log(this.a)
}
const object = {
    a: 1, 
    b: func
}

object.b()  // 1 (this->object)
Copy the code

The two “this” references objects, so we can understand that the function works the same whether it is defined inside or outside the object. Because functions that are properties of an object are independent of the object.

Note, however, that sometimes the this binding can be lost in an object, which is what we will use in the Apply or Call mode below.

Use the Apply or Call invocation pattern

Here’s an example:

function func() {
     console.log(this.a)
}
const object = {
    a: 1, 
    b: func
}
const fun = object.b;

fun()  // undefined
Copy the code

The value fun() prints is not 1 in the object, but undefined. This does not refer to an object. Let’s add a global a to the code and see what happens:

function func() {
     console.log(this.a)
}
const object = {
    a: 1, 
    b: func
}
const fun = object.b;

var a = 2;
fun()  // 2
Copy the code

Func prints the value of the global variable, 2, indicating that this refers to the external global variable. This situation is mainly caused by the loss of the THIS binding due to the implicit binding of this.

The result of the call to fun is different from that of the call to object.b, because the assignment cannot pass this to b as well

Refusal: resolve this issue with this display binding.

We can solve this by using call and apply and bind, where this in the function is shown as the first argument in the call. The following code:

function func() {
     console.log(this.a)
}
const object = {
    a: 1, 
    b: func
}
var a = 2;
const fun = object.b;

fun.call(object) ζˆ–θ€…  fun.apply(object) ζˆ–θ€…  const funb = fun.bind(object) ; funb() // 1
Copy the code

In this case, this refers to the a inside the object, which solves the problem of the lost this binding.

🌈 🌈 note:

  • bindIt provides an executable function, but it does not execute itself. We need to execute it manually.
  • callandapplyThey are provided as a function that can be executed immediately after bindingthisThe function is also executed immediately. That’s why we’re on the last one, rightbindMethod that needs to be called againfunb()Method.

A function call

This will also point to the global object. We can also think of this as: when there is no explicit call object, the line number of this is still global, so this is bound to the global window object.

Calling the constructor

Here’s an example:

function func(a) { this.b = a; console.log(b) } func(20); Const funb = new func(30) funb.b; / / 30Copy the code

As you can see, when the new operation is performed, a new object is created, and the this constructor is referred to the new object being created.

2. Explain how prototype inheritance works

About the prototype chain and the principle of its inheritance, Xiaobian in the previous article, in front of the part of the combination of pictures and text, has done a more detailed introduction, interested in children’s shoes can go to Chou, Xiaobian here is not much to introduce (and can be lazy).

3. What are closures, how to use them, and why

Have close package part, also be reflected in poison chicken soup.

4. What is the difference between synchronous and asynchronous functions

synchronous

Synchronous (blocking mode) means that when a request is sent, it needs to wait for a return before it can send another request. There is a waiting process. In addition, synchronization can also prevent the occurrence of deadlock, read dirty data.

asynchronous

Asynchronous (non-blocking mode) means that when a request is sent, there is no need to wait for a return, and the next request can be sent at any time. It doesn’t have to wait.

The difference: the most obvious one is one that needs to wait and one that doesn’t.

Extension: During the project, you can consider whether functionality is synchronous or asynchronous, depending on the requirements. In general, in order to shorten the waiting time of users, some functions are preferred to adopt asynchronous mode; However, for the operation such as database saving, the common method is synchronization.

5. The difference between host objects and native objects in JavaScript and build-in Objects

concept

  • The host objectHost objects are not native to the engine, but are registered by the host framework through some mechanismjsObjects in the engine;
  • Built-in objects: Objects that are created during engine initialization and are a subset of native objects;
  • Native objects: In addition to built-in objects, these include objects that are dynamically created at run time;

content

  • The original objectInclude:Object.Function.Array.String.Boolean.Number.Date.RegExp.Error.EvalError.RangeError.ReferenceError.SyntaxError.Typerror.URLErrorAnd so on;
  • Built-in objectsInclude:Global(global object),Math; (Note that all built-in objects are native objects)
  • The host objectIncludes: there are host-provided objects in the browserwindowObject and all child objects below it (for exampledomEtc.), innodeIs in theglobalAnd its children, which also contain custom class objects.

The difference between

  • Built-in objects are a subset of native objects; The former always creates objects during engine initialization, while the latter includes objects that are dynamically created during runtime.
  • The host object is not a native object of the engine, but an object registered to the JS engine by the host framework through some mechanism.

Function Person(){}, var Person = Person(), var Person = new Person();

  • The first:function Person(){}Is a declaration calledPersonThe function of;
  • The second:var person = Person()It’s called directlyPersonFunction, and assign the returned value as a value to the variableperson;
  • The third:var person = new Person()I created aPersonInstance object;

7. What is the variable declaration upgrade (reactor-based)?

Let’s start with an example:

console.log(num); //undefined
var num = 5;
console.log(num) // 5
Copy the code

At this point, those of you who have the basics might see why. That’s right, variable declaration promotion! The life cycle of a variable consists of three phases

  • The statement— Start by creating a new variable, such as:var num;
  • Initialize theInitialize a variable and assign a value to it, for example:num = 5;
  • use— Use the value of a variable, for exampleconsole.log(num);

The above example is equivalent to:

var num; console.log(num); // Undefined because num is promoted, but the value is not promoted, so undefined num = 5; console.log(num) // 5Copy the code

🌈🌈 Note: If the variable is in function scope, then its scope is function scope. Otherwise, it is global scope.

expand

Functions that extend 1 take precedence

Function declarations and function expressions are syntactically equivalent, but the js engine loads them differently. Simply put: function declarations are promoted to the top of their scope, but function expressions are not.

Specific can see the following two points:

  • Function declarations are promoted, but the body of the function expression is not promoted;
  • The function isjavascriptWhen a variable name has the same name as a function, the function declaration takes precedence over the variable declaration and ignores the variable declaration with the same name.

Extension 2 lets, const, and var

To make a long story short, let and const declarations form block-level scope, there is no variable promotion, and the same variable (or constant) cannot be declared repeatedly. Variables declared by var are mounted on window, have variable promotion and can be named repeatedly.

What is “use strict”? ? The pros and cons of using it

“Use strict” — Strict mode, a mode added by ES5 to allow javascript to run under more strict conditions.

Advantages (purpose of establishment)

  • eliminatejsSome of the grammar is not reasonable, not rigorous, reduce some weird behavior;
  • Eliminate some of the code running unsafe, to ensure the safety of code running;
  • Improve compilation efficiency and increase running speed;
  • For future new releasesjavascriptLay the groundwork;

🌈🌈 Note: After testing, the current IE6-9 does not support strict mode.

disadvantages

Now the website js will generally be compressed, compression process, some files use strict mode, some do not. In this case, when a file is merged in strict mode, the string is in the middle of the file, not only does it not indicate strict mode, but it also wastes bytes after compression.

What is an Event Loop?

Javascript is executed single-threaded, from top to next run. There are two tasks in JS, macro task and micro task. In general, macros are executed first (i.e., all synchronized code is executed in the first place). When microtasks are encountered, they are queued and executed after the macro task is executed. After the execution of the microtask, proceed to execute the macro task, and then execute all microtasks again.

The simple understanding is: macro task -> micro task -> macro task -> micro task;

Finally detailed implementation mechanism, interested small partner xiaobian suggested that please move to poison chicken soup Chou Chou.

10. What are the differences between bind, call and apply

The similarity

  • The first argument to both of them isthisObject to point to;
  • It’s all about changing the functionthisPointing to the;
  • Can use the following parameters pass parameters;

The difference between

  • implementationUse:callandapplyThe function can then be executed automatically, but usingbindManual execution is required;
  • Parameter receiving aspect:callandapplyThe first argument received is the scope in which the function is run. The difference is that when the second argument is received,applyI’m receiving an array, andcallYou receive a list of parameters that correspond to the function one to one.

🌈🌈 Note: Call and apply extend the scope of functions.

Application scenarios

  • If you don’t need to care how many arguments are passed into the function (or if there are many arguments), you can use this optionapply;
  • If you are sure how many arguments (or fewer) the function can take, and you want to explicitly express the object relationship between the parameters and the arguments, choose this optioncall;
  • If you want to call the method in the future and do not need to get the result of the function immediately, you can use this optionbind;

🚚… α΄… ᴜ α΄… ᴜ!

11. πŸ€₯ What is event delegate and how can bubbling events and default events be prevented

Concept: Event bubbling is when the deepest nested element fires an event, which then fires on the parent element in the order of nesting. The event delegate uses the event bubbling principle to let the event triggered by itself be executed by its parent element instead.

Bubble blocking: use event.cancelbubble = true or event.stoppropgation () (lower than IE9).

Default event blocking mode: e.preventDefault(); Or return false; .

12. How do I check if a number is an integer

An easy way to do this is to take the number modulo 1 and see if there is a remainder. Look at this code:

function isInt(number) { return number % 1 === 0; }; The console. The log (isInt (2.1)); // false console.log(isInt(2)); // trueCopy the code

What is IIFE (call function expression immediately)

It was the immediately-invoked Function Expression, known as IIFE for short. This means that the function is executed immediately after it is created. Look at the following code:

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

This immediate call function expression is generally used to avoid fouling the global namespace. Because all variables inside an IIFE (like any other normal function) are invisible outside of its scope.

14. Prototype design pattern

The stereotype pattern can be used to create new objects, but instead of creating an initialized object, it creates an object that is initialized using the value of the stereotype object. The archetypal pattern also becomes the attribute pattern.

The prototype pattern is useful in initializing business objects where the values match the default values in the database. The default values in the prototype object are copied to the newly created business object. Js currently uses this pattern when constructing new objects and their prototypes.

The archetypal pattern consists of the following main characters:

  • Abstract prototype class: specifies the interface that a concrete prototype object must implement;
  • Concrete prototype class: implements the abstract prototype classclone()Method, which is a replicable object;
  • The access class: using a concrete prototype classclone()Method to copy a new object;

15. How JSONp works, and why it’s not real Ajax

Jsonp principle: using the browser can dynamically insert a section of JS code and execution;

Why not real AJAX

  • First of all,ajaxandjsonpIn the invocation mode, although they look similar (the purpose is the same, both are a requesturlAnd then process the data returned by the server), butajaxandjsonpIt’s essentially something different;
  • What’s different? Different core!ajaxThe core is throughXmlHttpRequestGet content other than this page, andjsonpAt its core is dynamic addition<script>Tag to call the server providedjsThe script.
  • In addition, it’s important to note thatajaxandjsonpThe difference is not whether it is cross-domain or not. becauseajaxCross-domain can also be implemented through server-side proxies,jsonpIt does not exclude the acquisition of data in the same domain. Also,jsonpIt’s a way or an optional agreement, likeajaxAgain, it doesn’t have to bejsonpFormat to pass data;
  • jsonpOnly supportgetThe request,ajaxsupportgetandpostThe request.

16. What are the event flow models in Javascript

  • “Event Bubble”: When an event is triggered on a node, events of the same type on its ancestor nodes are triggered successively from the current node untilDOMThe root node. (Step by step)
  • Event Capture: When an event is triggered on a node, the event is triggered fromDOMThe root node, in turn, triggers events of the same type on its ancestor nodes until the current node itself. (Step by step)
  • DOM Event Flow:domBoth event models are supported, but capturing events starts first, fromdocumentIt begins and ends withdocument.domWhat’s unique about the model is that text can also trigger events. To put it simply, there are three stages:Event capture.The target stage.The event bubbling

17. Exactly what the new operator does

First of all, we need to understand that the main function of the new keyword is inheritance.

For const a = new Foo(); , new. The following code:

const obj = new Object(); // Declare a new null object obj obj.__propto__ = person.prototype; // make obj's __proto__ refer to the function's prototype person.call (obj); Person = obj; person = obj; // Assign the obj object to the person objectCopy the code

So let’s get this straight. How many stages does New go through? (4)

  • Create an empty object;
  • Set up the prototype chain;
  • letFuncthethisPoint to theobjAnd performFuncThe body of the function.
  • judgeFuncThe return value type of the constructor;

18. What are the methods of js lazy loading?

  • deferProperties (pageloadLater execution) : The script is delayed until the entire page has been parsed. If it’s setdeferProperty, which tells the browser to download now, but delay execution. Pay attention todeferProperty applies only to external script files.
  • asyncProperties (pageloadPre-execution) : Loads pages and other content asynchronously in order not to have pages waiting for scripts to download and execute.asyncThe same applies only to external files (does not affect page loading, but does not control the order of loading).
  • Dynamically createDOMWay;
  • usejQuerythegetScript()Methods;
  • usesetTimeoutDelay method;
  • letjsThe file is loaded last.

19. What are the advantages and disadvantages of Flash and Ajax, and how to choose between them

  • In the Flash,:flashIt handles multimedia, vector graphics, and access machines; But forCSS, the text processing is not easy to search;
  • For Ajax:AjaxrightCSS, text processing has good support, also support search; But for multimedia, vector graphics and access to machines and so on;

Thing in common:

  • Deliver messages with no refresh on the server;
  • Can detect the user offline and online status;
  • Can operateDOM;

20. How are cookies stored on the client

Cookies are text files temporarily placed on our computers by the server so that the server can identify our computers.

When we browse the website, the Web server will first send a small part of information to our computer, and cookies will help us to record the text or some choices we print on the website. When we visit the same website again, the Web server will first check whether there are cookies left by it last time.

If so, it will judge the user based on the content in the cookies, so as to promote the corresponding web content to us.

🚚… α΄… ᴜ α΄… ᴜ!

21. 🀨 What is Json

  • jsonIs a lightweight data exchange format;
  • Independent of the language platform, parsers and libraries support many different programming languages;
  • Its syntax represents three types of values: simple values (number.string.boolean.null), arrays, objects;

22. The difference between threads and processes

A program has at least one process, and a process has at least one thread. The partition scale of threads is smaller than that of processes, which makes the concurrency of multithreaded programs high. Here we can simply think of processes as trains and threads as cars.

The difference between:

  • Threads run under a process and cannot run separately (a single car cannot run);
  • A process can contain multiple threads (a train has many cars);
  • It is difficult to share data between different processes (it is difficult for passengers to switch from one train to another while the train is moving);
  • The ease with which threads can share data in the same process (it is easy for passengers to switch from one carriage to another on the same train);
  • Processes consume more computer resources than threads (it takes more effort to run a car just to run it, or to run it with power);
  • Processes do not interfere with each other, but if one thread of the same process fails, the whole process will fail (a train of the same class will be suspended if one of its carriages fails, such as catching fire);
  • Processes can scale to multiple machines, and threads can scale to multiple cores at mostcpu. (Different trains can run on different tracks, while cars of the same train can only run on the same track as the current train);
  • The memory addresses used by processes can be locked, meaning that when one thread uses some shared memory, other threads must wait for it to finish before they can use it. (e.g., using the bathroom on the train – “mutex”);
  • A process can use a limited amount of memory (e.g., a sleeper on a train, which allows only a maximum number of people to sleep, and if it is full, it has to wait until a bed is available — a “semaphore”);

23. What should be considered if web content needs to support multiple languages

  • Using the character set selection, utF-8 encoding is selected.
  • Language writing habits and navigation structures;
  • Database-driven website;

24. Some writing principles of javascript

  • Do not declare multiple variables on the same line;
  • use= = = ε’Œ! = =To make a comparison;
  • Use literals to create arrays and objects insteadnew ArrayIn this form;
  • switchStatement must bedefaultBranch;
  • fon-inThe variable in the loop, withvarKeyword description scope, prevent variable contamination;
  • Use ternary expressions whenever possibleif.. else..Conditional statement;
  • Compare the data types below6The situation isfalse.false,"",0,null,undefined,NaN; The rest aretrue;
  • For data type detectiontypeofFor object type detectioninstanceof;
  • Asynchronously loading third-party content;

.

25. What are closures, what features do they have, and how do they affect the page

Closures are functions that can read the internal variables of other functions so that the functions are not collected by GC. But when closures are abused, they can cause memory leaks;

26. The difference between document load and Document Ready

  • document load: is in the structure and style, externaljsExecute js after the image is loaded.
  • document readyIs:domA method that executes when the tree is created. There is no such method native.

27. How do I interrupt ajax requests

  • Set the timeout period toajaxAutomatic disconnect;
  • Manual stopajaxRequests, at their core, are callsXMLThe object’sabortMethod,ajax.abort();

28. Macro tasks and microtasks

  • Macro tasks: Tasks executed on the current call stack are called macro tasks. Including the overall codescript.setTimeout.setInterval;
  • Microtask: The current macro task (in this event loop) is completed, and the task that needs to be executed before the next macro task starts is a microtask. Contains callback events,Promise.process.nextTick(node. Js);

🌈🌈 Note: Events in macro tasks are placed in the callback queue and maintained by the event-triggering thread; Events for microtasks are placed in the microtask queue, which is maintained by the JS engine thread.

29. The difference between GET and POST

  • getThe parameter is passed through the URL in the address bar. If yes, you can see it directlygetThe parameter passed,postParameter pass mode The parameter URL is not visible.getPut the requested data inURLAfter through?Connect, pass through&Parameter segmentation.psotStore parametersHTTPThe body of the bag;
  • getData is passed byURLFor passing, the length of the transmitted data is subject toURLThe size limit,URLThe maximum length is2048A character.postNo length limit;
  • getRolling back has no effect,postThe rollback will result in a new submission.
  • getRequests can be cached,postCannot be cached;
  • getRequest onlyURLCoding,postSupport a variety of encoding;
  • getOnly supportASCIICharacters,postThere is no character type limit for submission;
  • getThe requested record stays in the history,postRequests do not stay in the history;

30. Common HTTP response codes and their meanings

(1) 1xx (temporary response)

  • 100Requesters should continue to make requests.
  • 101(Switch protocol) : The requester has asked the server to switch protocol, the server has confirmed and is ready to switch.

(2) 2XX (success)

  • 200: The request succeeds and returns the correct interface result;
  • 201: indicates that the resource is correctly created.
  • 202: The request is correct, but the result is being processed. In this case, the client can continue the request through polling or other mechanisms.
  • 203: Unauthorized information. The server successfully processed the request, but the returned information may have come from another source.
  • 204: No content. The server successfully processed the request but returned no content.
  • 205: reset the content, the server successfully processed the request, the content is reset;
  • 206The server successfully processed part of the request.

(3) 3xx (redirected)

  • 300: The request succeeds, but multiple results are returned;
  • 301: The request succeeded, but the resource was permanently transferred.
  • 302: temporary move, the requested page temporarily jump to other pages, that is, temporary redirection;
  • 303: Use get to access the new address to obtain the resource;
  • 304The requested resource has not been modified.
  • 305: Using the proxy, the requester should use the proxy to access the page;
  • 306: temporary redirection, where the requested resource temporarily responds from another location;

(4) 4xx(request error)

  • 400: An error occurs in the request. For example, the request header is not equal.
  • 401: No certification information provided. I didn’t bring it with me when I askedTokenAnd so on;
  • 402: is the status code to be reserved later;
  • 403: The requested resource is not allowed to be accessed and has no permission.
  • 404: Page not found;
  • 405: Method disabled, the server disabled the method specified in the request;
  • 406: Not accepted, cannot use the requested content to respond to the requested page;
  • 407: The requester needs to use proxy authorization;
  • 408: The server request times out.
  • 409The server has a conflict while completing the request.
  • 410The requested resource has been permanently deleted.
  • 411: A valid length is required. The server will not accept requests that do not contain a valid content-length header field;
  • 412: The server does not meet one of the prerequisites set by the requester in the request;
  • 413: The request entity is too large to be processed by the server.
  • 414: The requested url is too long and the server cannot process it;
  • 415The requested format is not supported by the requested page.
  • 416: The page cannot provide the requested scope;
  • 417: The server does not meet the requirements of the expected request header field;

(5), 5xx (server error)

  • 500The server has an internal error and cannot complete the request.
  • 501: The request has not been implemented, the server does not have the full request function;
  • 502: Error gateway. The server acts as the gateway or proxy and receives an invalid response from the upstream server.
  • 503: The service is unavailable.
  • 504: The gateway times out and the server acts as the gateway or proxy. However, the request is not received from the upstream server in time.
  • 505:HTTPVersion not supported, server does not support the one used in the requestHTTPProtocol version.

🚚… α΄… ᴜ α΄… ᴜ!

31. 😀 The difference between Internet Explorer and DOM event streams

  • In order of execution:IEIt’s a bubble type event, andDOMIs capture first and then bubble event;

Let’s look at an example:

<div> <button> click </button> </div> </body> // DOM event model: body->div->button->button-> button->div->bodyCopy the code
  • In terms of parameters, an earlier versionieThere is no callback function, it can only be bubbled;
  • From the first parameter whether to add “on” problem, the earlier version of IE does not supportaddEventListener()To supportattachEvent, the first parameter needs to be addedon;
  • From this point of view.IEPoint to thewindows, does not point to the triggered function;

What kind of language is javascript

  • An interpreted scripting language where code cannot be precompiled;
  • Mainly used tohtmlAdd interactive behavior to the page;
  • Can be directly embedded intohtmlPage, or as a separate JS file. It is recommended to write it in a separate document, which is conducive to the separation of structure and behavior and is conducive to maintenance.
  • Cross-platform, the ability to run on multiple platforms with support from most browsers, for examplewindows.linuxAnd so on;

33. What are DOM and BOM

First, we need to know that javascript is composed of ECMAScript, DOM, and BOM.

  • ECMAScriptIs a language, is a description of the specified syntax, operations, keywords, statements,javascriptTo achieve theECMAScript;
  • DOMIs the document object model, including obtaining elements, modifying styles and operating elements, and other three aspects of content, is usually we use the most operations, it provides a lot of compatibility of writing;
  • BOMIs the browser object model, which includes some of the actions of the browser,window.onload.window.openWait for browser time, listen for window changesonresize, and listen for scroll eventsonscrollAnd so on;

34. How to realize the communication between multiple labels

  • Call the localStorage;

(1) Use localStorage in a label. SetItem (key, value) Add (delete or modify) content;

(2) On the other TAB page, listen for storage events.

(3), get the value of localStorage storage, you can realize the communication between pages without.

  • Call the cookie + setInterval ();

(1) The information to be transmitted is stored in cookies. You can set the information to be read regularly to obtain the information to be transmitted at any time.

  • Use Webworker;

(1) Webworker, as a new feature of the browser, can provide an additional thread to execute some JS code, and has no impact on the browser user interface;

(2) Ordinary Webworker can be created with new worker(), which is exclusive to the current page. Then there are shared workers (SharedWorker), which can be used by multiple tabs and iframe.

  • Use SharedWorker;

(1) SharedWorker can be used by multiple Windows, but these tabs must be same-origin (same protocol, host and port number);

35. What operations can cause memory leaks

A memory leak is when a chunk of allocated memory is neither used nor reclaimed until the browser process ends.

The following causes memory leaks:

  • Excessive use of closures can cause memory leaks (Resolve: define the event handler external, remove the closure, or remove the pair in the external function that defines the event handlerdom);
  • Console logs (resolve: remember to delete redundant console prints after project completion);
  • A loop, where two objects refer to each other and keep each other;
  • setTimeout(Fix: try not to define the first argument as a string);
  • Unexpected global variables can also cause memory leaks (Resolve: avoid using strict mode).
  • Didn’t cleanDOMElement (resolve: manually delete);

36. Several ways of js garbage collection

Javascript has an automatic garbage collection mechanism, which is performed periodically at fixed intervals.

There are two common garbage collection mechanisms: tag cleanup and reference counting.

Mark clear

How it works: When a variable enters the environment, mark the variable as “entering the environment.” When a variable leaves, it is marked “out of the environment.” Those marked “out of the environment” reclaim memory.

Workflow:

  • The garbage collector, at runtime, marks all variables stored in memory;
  • Untag variables in the environment and variables referenced by variables in the environment;
  • Variables that are tagged are considered to be ready to be deleted;
  • The garbage collector does the cleanup, destroying the marked values and reclaiming the memory space they occupy.

Reference counting

Principle: Track the number of references to each value, declare a variable, and assign the reference type to this variable, then the number of references to this value +1, when the value of the variable changed to another value, then the number of references to this value -1, when the number of references to 0, then reclaim.

Workflow:

  • A variable is declared and a value of a reference type is assigned to it. The number of times the reference value is referenced is1;
  • The same value is changed byAssigned toAnother variable, the number of times this reference type is referenced on this occasion+ 1;
  • When the variable containing the value of the reference type is reassignedThe assignment intoAnother value, the number of times this reference value is referenced- 1;
  • When the number of references becomes 0, the value is currently inaccessible.
  • The next time the garbage collector runs, it frees the reference the number of times0The memory occupied by the value of;

37. What is in memory? What doesn’t go in memory?

  • Basic types (Boolean.String.Number.Null.Undefined.Symbol(New))Save it in memory. Assigning a value of a basic type from one variable to another creates a copy of that value;
  • Reference data types (object) is an object,Stored in the heap memory.

🌈 🌈 note:

  • A variable that contains a value of a reference type actually contains not the object itself, but a pointer to that object. When you copy a value of a reference type from one variable to another, you’re actually copying a pointer, so both variables end up pointing to the same object;
  • javascriptDirect access to locations in memory is not allowed, that is, the memory space of the operation object cannot be accessed directly. When you manipulate an object, you are actually manipulating a reference to the object rather than the actual object.

38. The difference between heap and stack

(1) The difference between heap and stack space allocation

  • Heap (operating system) : generally allocated by the programmer to release, if the programmer does not release, the end of the program may be recycled by the OS, allocation is similar to a linked list;
  • Stack (operating system) : automatically allocated by the operating system to release, hold function parameter values, local variable values, etc. It operates like a stack in a data structure;

(2) The difference between heap and stack caching

  • The heap is stored in a level 2 cache, and the declaration period is determined by the virtual machine’s garbage collection algorithm (in this case, orphan objects are not recycled). So calling these objects is relatively slow;
  • The stack uses the level 1 cache, which is usually in the cache space when the call is made, and is released immediately after the call.

(3), the difference between heap and stack structure

  • Heap (data structure) : The heap can be thought of as a tree, such as heapsort;
  • Stack (data structure) : is a kind of advanced data structure;

39. What happens when the URL is entered into the browser and the entire page is displayed in front of the user (full explanation)

(1) DNS resolution

  • Check the browser’s ownDNSThe cache.
  • If no, search for the operating systemDNSThe cache.
  • If not, try to readhostsFile;
  • If no, configure the local preferenceDNSThe server initiates a request;
  • .winIf the system is not good enough, you can find the operating systemNetBIOS name cacheOr querywinsServer or broadcast to find or read LMHOSTS files;

(If none of the above, parse fails)

(2) TCP three-way handshake

(3) The browser sends HTTP requests to the server

Once the TCP link is established, the Web browser sends a request command to the Web server.

(4) The browser sends the request header information

After the browser sends its request command, it sends some other information to the Web server in the form of a header, and then the browser sends a blank line to inform the server that it has finished sending the header.

(5) The server processes the request

After the server receives the HTTP request, it makes sure to process the request with the appropriate glance. After reading the parameters and performing a logical operation, the specified data is generated.

(6) The server responds

After the client sends a request to the server, the server responds to the client.

(7) The server sends the response header

Just as the client sends information about itself with the request, the server sends data about itself and the requested document to the user with the reply.

(8) The server sends data

After the Web server sends the message to the browser, it sends a blank line to indicate the end of sending the header. It then sends the actual data requested by the user in the format described in the Content-type reply header.

(9) TCP close (four waves)

Typically, once the Web server sends the request data to the browser, it closes the TCP link. If the browser or server adds Connection:keep-alive to its header, it will remain in a persistent state. That is, the TCP Connection will remain open after being sent, and the browser can continue sending requests through fairchild’s link.

(Advantages: Staying connected saves time creating a new link for each request and saves Internet broadband)

40. What are the methods of inheritance

  • Prototype chain inheritance;
  • Constructor inheritance;
  • Instance inheritance;
  • Combination inheritance;
  • Copy inheritance;
  • Parasitic combination inheritance;

🚚… α΄… ᴜ α΄… ᴜ!

41. πŸ₯΄JavaScript is faster than ASP scripts

In general, javascript is faster. Javascript is a client-side language, so it does not require the assistance of a Web server to execute. ASP, on the other hand, is a server-side language and therefore always slower than javascript. Note, however: javascript can now also be used with server-side languages (such as Nodejs).

The difference between Java and JavaScript

  • First of all,javaIt’s a very complete, mature programming language; By contrast,javascriptIs one that can be introducedHTMLPage programming language. The two languages are not completely interdependent, but are really designed for different purposes.
  • Second,javaIs a kind of object-oriented programming (OOPS) or structured programming languages, similar toC++andC; whilejavascriptIs a client-side scripting language, known as unstructured programming.

43. What is negative infinity

Negative infinity is a number in javascript that can be obtained by dividing a negative number by zero.

44. What are undeclared and undefined variables

  • An undeclared variable is one that does not exist in the program and is declared. If the program tries to read the value of a declared variable, the run will report an error.
conosle.log(b);

// Uncaught ReferenceError: conosle is not defined
    at <anonymous>:1:1
Copy the code
  • Undefined variables are variables declared in a program but not yet assigned any value. If the program uses the value of an undefined variable, it returns oneundefined.
let c;
console.log(c);  // undefined
Copy the code

45. There are several timers in javascript and how do they work

Timers are used to execute a piece of code at a set time, or to repeat the code at a given interval. This is done with the setTimeout, setInterval, and clearInterval functions.

  • setTimeout(function.delay) function to move a timer that calls a particular function after the delay;
  • setInterval(function.delayThe) function is used to perform a given function repeatedly in the delay mentioned, stopping only when canceled;
  • clearInterval(idThe) function indicates that the timer stops;

🌈🌈 Note: The timer runs within a thread, so events may need to be queued for execution;

46. What is the difference between ViewState and SessionState

  • ViewState: specific to the page in the session;
  • SessionState: specific to available inwebUser-specific data accessed on all pages in the application;

47. What is the function of the delete operator

The delete operator is used to delete all variables or objects in a program, but not variables declared with the var keyword.

48. What is the result of 5 + 8 + ‘7’ and 5 + ‘8’ + 7

console.log(5 + 8 + '7'); // 137 console.log(5 + '8' + 7); / / 587Copy the code

You can think of it this way: consecutive integers can be added directly, and strings can be directly connected.

49. What are the drawbacks of using innerHTML in JavaScript

  • Content is everywhere;
  • Can’t be like ‘append toinnerHTML‘;
  • Even using+=like "innerHTML = innerHTML + 'html'", the old content will still behtmlReplace;
  • The wholeinnerHTMLContent is reparsed and built into elements, so it’s much slower;
  • innerHTMLValidation is not provided, so it is possible to insert valid and destructive ones into the documentHTMLAnd cut it off;

50. There are several different types of errors in JavaScript

JS error types generally include six common derived error types and manually thrown error types.

(1) Several common types of errors

  • SyntaxError: SyntaxError, generally a SyntaxError that occurs while parsing code;
  • ReferenceError: ReferenceError, a general guide to an error that occurs when a variable does not exist.
  • TypeError: a TypeError occurs when a variable or parameter is not of the expected type.
  • EvalError eval(): A function execution error, usually wheneval()Thrown when a function is not executed correctlyevalErrorError;
  • RangeError: a RangeError, typically an error that occurs when a value is outside the valid range.

🚚… α΄… ᴜ α΄… ᴜ!

51. πŸ₯± Deferred scripting in JavaScript

Typically, when a script is first loaded on a page, the HTML code for the page will pause parsing during loading until the script is loaded.

So there will be such a situation, when the server speed is very slow or the script is heavy, will cause a page delay. With Defer, the script is deferred until the HTML parser has finished running. This greatly reduces load time and improves display speed.

52. What are decodeURI () and encodeURI ()

EncodeURI () is used to convert the URL to hexadecimal encoding, while decodeURI() is used to convert the encoded URL to a normal URL.

53. What is a hash table

A hash table (also known as a hash table) is a data structure that is accessed directly based on key values. That is, it accesses records by mapping the key to a location in the table to speed up lookups. This mapping function is also called a hash function, and the array of records is called a hash table.

54. There are several types of nodes

Generally, a node has at least nodeType, nodeName, and nodeValue.

The nodeType attribute returns the constant value of the nodeType. Different types correspond to different constant values, and the 12 types correspond to constant values from 1 to 12, as follows:

  • Element nodes:Node.ELEMENT_NODE(1);
  • Attribute node:Node.ATTRIBUTE_NODE(2);
  • Text node:Node.TEXT_NODE(3);
  • CDATA node:Node.CDATA_SECTION_NODE(4);
  • Entity reference name node:Node.ENTRY_REFERENCE_NODE(5);
  • Entity name node:Node.ENTITY_NODE(6);
  • Processing instruction node:Node.PROCESSING_INSTRUCTION_NODE(7);
  • Comment node:Node.COMMENT_NODE(8);
  • Document node:Node.DOCUMENT_NODE(9);
  • Document type node:Node.DOCUMENT_TYPE_NODE(10);
  • Document fragment node:Node.DOCUMENT_FRAGMENT_NODE(11);
  • DTD declaration node:Node.NOTATION_NODE(12);

(This section is an expanded content from Baidu 🌻🌻)

55. Differences between innerHTML and outerHTML

  • innerHTML(the contents contained within the element)
  • outerHTML(itself and the content within the element);

56. Difference between offsetWidth and clientWidth clientHeight

  • offsetWidth/offsetHeight (contentWidth/height +paddingWidth/height +borderWidth/height);
  • clientWidth/clientHeight (contentWidth/height +paddingWidth/height);

57. Several ways to reduce page load times

  • The compressionCSS,JSFile;
  • mergeCSS,JSFile reductionhttpRequests;
  • externalJS,CSSPut at the bottom;
  • To reduceDOMOperations, where possible using variables instead of unnecessaryDOMOperation;
  • Optimize image files to reduce their size, especially thumbnails;
  • Using multiple domain names to load multiple files and images in a web page;
  • Server EnabledgzipCompression;

58. Describe how AJAX works

  • Step 1: CreateAJAXObject (XMLHttpRequest/ActiveXObject(Microsoft.XMLHttp));
  • Step 2: UseopenOpen the connection in the formatopen(Request mode, ‘request path’, synchronous/asynchronous);
  • Step 3: Sendsend();
  • Step 4: WhenajaxObject completes step 4(onreadystatechange), data is received. Then determine the object status code(readystate)When the status code is the received status code successfully,HTTPThe response was fully received. To determinehttpResponse status (200-300.Or between304), (cache) converts the data obtained by the callback function to a string format(responseText) 。

Disadvantages:

  • Not friendly to search engines;
  • Limitations of cross-domain problems;
  • In order to achieveajaxThe cost of the forward and backward function is relatively large;

59. HTTP cache mechanism, and how to implement from cache in 200 state

meaning

Browser Caching speeds up browsing. The Browser stores the most recently requested document on the user disk. When the user accesses the document again, the Browser displays the document from the local disk, improving the page loading rate.

The role of the cache

  • Reduce latency to make your site run faster and lead to a better user experience;
  • Avoid network congestion, reduce the number of requests, reduce the output bandwidth;

Realization means

Max-age in cache-control is an important method to implement content cache. There are three common policies:

  • max-ageandETagThe combination of;
  • onlymax-age;
  • max-ageandLast-Modified(if-modified-since);

expand

Here, expand on the mandatory cache (200) and negotiated cache (304) sections.

  • Force caching (also called strong caching)When the browser requests a file, the server is thererespone headerThe cache configuration is done for this file. The force cache does not send a request to the server and reads the resource directly from the cachechromeThe consolenetworkYou can see the request return in the option200Status code;
  • Negotiate the cache: Mandatory caching sets the expiration time for resources. If the expiration time is not expired, it can be said that the user is self-sufficient. However, when the resource expires and the server needs to be requested, the process of requesting the server can be set to a negotiated cache. Negotiation caching is where the client and server interact. The negotiation cache will cache information inEtagandLast-ModifiedSend the request to the server for verification and return the status code304, the browser can use the cache directly.

Common: both read data from the client;

Difference: Strong caches do not make requests, negotiation caches do.

The header arguments in the cache:

(1) Force cache:

  • Expires(commonly used) :response headerWhen the browser reloads the resource, if it is within this expiration time, the strong cache will be hit.
  • Cache-Control(Common) : On duty set tomax-age=120The correct return time of the request (also recorded by the browser) is2Reload the resource within minutes, and you hit the strong cache.
  • No-cache: The local cache is not used. You need to use cache negotiation to verify the expiration;
  • No-store: Cannot be cached.
  • Public: Both the client and proxy server can cache.
  • Private: Only the client cache can be used.

(2) Negotiation cache

  • EtagThat filehash, unique for each file.webWhen the server responds to a request, it tells the browser the unique identifier of the current resource on the server (the generation rule is determined by the server).
  • If-None-Match: When the resource expires (useCache-ControlIdentification of themax-age), found that the resource hasEtagDeclaration, then again towebServer request with the aboveIf-None-Match(value of Etag).webThe server found a header after receiving the requestIf-None-MatchThen it compares with the corresponding check string of the requested resource to determine whether the negotiated cache is matched.
  • Last-Modify/If-Modify-Since: File modification time, accurate to seconds. The first time a browser requests a resource, the server returns itheaderWill addLast-Modify.Last-modifyIs a time that identifies the last time the resource was modified; When the browser requests the resource again,requestIs included in the request headerIf-Modify-Since, which is returned before cachingLast-Modify. Server receivedIf-Modify-SinceThen, determine whether the cache is hit according to the last modification time of the resource.

🌈 🌈 note:

  • EtagIs better thanLast-Modified;
  • In terms of priority, server verification takes precedenceEtag;
  • In terms of performance,EtagTo be worse thanLast-Modified.

60. What is the virtual DOM, why is it used, and how is it different from the real DOM

Meaning and Usage

The virtual DOM is a memory representation of the real DOM. It is a programming concept and a pattern. It is used to determine whether the DOM has changed and which parts need to be rerendered. This eliminates the need to manipulate the real DOM and greatly improves React performance.

The virtual DOM uses the Diff algorithm. When we modify a part of the content for many times, we first carry out the same layer comparison in the virtual DOM tree from top to bottom (without affecting the real DOM). The upper layer changes, and the lower layer renders again until the final modification is completed, and then renders in the real DOM.

The reason for using virtual DOM is that it can greatly reduce the backflow and redrawing problems of DOM nodes, save resources and improve operation efficiency.

The difference between

  • virtualDOMWill not rearrange and redraw;
  • virtualDOMMake frequent changes, and then compare and change the real one at a timeDOMIn the need to modify the part, finally backflow and redraw, effectively reduce the excessiveDOMNode backflow and redraw resource consumption;
  • virtualDOMEffective reduction of large area (trueDOMNode) backflow and redraw as it ends with realityDOMTo compare the difference, you can render it locally.

🚚… α΄… ᴜ α΄… ᴜ!

61. 🀫 cross-domain and solutions

Different protocol, domain name, and port number: cross-domain (also the same protocol, domain name, and port number: Same-origin policy)

There are several ways to solve cross-domain problems:

  • document.domain + iframe(Only if the primary domain is the same);
  • Dynamically createscript;
  • location.hash + iframe;
  • window.name + iframe;
  • postMessage(HTML5In theXMLHttpRequest Level 2In theAPI);
  • CORS(Cross-domain resource sharing);
  • jsonp;
  • websockets;

62. Cliches about CSRF and XSS

XSS (Cross Site Scripting)

Cross-site scripting (XSS) attacks, in which hackers insert malicious script code into the page to steal user information (note that the operation is the user, the attack is just code embedding).

Preventive measures:

  • The necessary escape of the input and output results;
  • Try to usepostforgetLimit the length of the path as much as possible;
  • usehttponlyThe hacker obtains the user through the scriptcookieThe data.
  • In the customer itself, develop good habits, improve vigilance, do not randomly point to strange links;

CSRF (Cross-site Request Forgery)

Cross-site request forgery, where a hacker masquerading as a user performs malicious and illegal actions that are not voluntary (note, in this case, a hacker masquerading as a user).

Preventive measures:

  • Use verification code;
  • usetoken idThe token.
  • Judging the requestreFererIs it correct;

The difference between

  • CSRFYou need to log in and operate,XSSDon’t need;
  • CSRFYes request pageapiTo perform illegal operations,XSSIs to implant to the current pagejsScripts modify the content of the page.

63. What about AMD and CommonJS

Modular programming specification for browser-side asynchronous and server-side synchronous.

CommonJS: is a module form defined to solve the scope problem of JavaScript, so that each module can be executed in its own namespace. The main content of the specification is that a module must export variables or interfaces through module.exports, import output from other modules into the current module scope through require(), and module identifies the module itself.

AMD: a globally defined, export-function provides two external variables, module and exports, in which modules are placed. The output value of the module is placed in module.exports, and the module is loaded.

64. There are several anonymous function (function with no defined function name) use cases

  • Define the callback function;
  • Execute the function immediately;
  • Function as a return value;
  • Use method:var func = function() {};Defined function;

65. The difference between null, undefined, and undeclared and how to detect it

The difference between:

  • Null: undefined property;
  • undefined: defines but is assigned toundefined;
  • undecleared: javascriptAccess will not report errors;

Detection method:

  • nullIt’s a special kind ofobject, indicates no value;
console.log(typeof null); // object const a = null; if(! a && typeof(a) ! == 'undefined' && a! ==0) { alert('a is null') } else { alert('a is not null') }Copy the code
  • undefined: is a declared but unassigned variable;
const a = undefined;
if(typeof(a) === 'undefined') {
    alert('a is undefined')
} else {
     alert('a is not undefined')
}
Copy the code
  • undeclared:undeclaredIs a syntax error, not a data type, and is an undeclared and unassigned variable.

🌈🌈 Note that the JS engine will not report an error when JavaScript accesses it. It will treat it as a global variable, that is, as a property of window.

67. The difference between mutable and immutable objects

  • MutableIn:JSIn, the object is the data of reference type. Its advantage is that frequent modification of the object is based on the original object, and it does not need to be recreated. In this way, memory can be effectively utilized and memory space will not be wasted.
  • Immutable: Modify one at a timeimmutableObject, a new immutable object is created, and operations on the new object do not affect the data on the original object.

68. What are the pros and cons of using Promises instead of Callbacks

Promise is a solution to asynchronous programming that is more rational and powerful than the traditional solution callback functions and events. It was first proposed and implemented by the community, and ES6 wrote it into the language standard, unifying usage and providing Promise objects natively.

A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations. Promise provides a uniform API so that various asynchronous operations can be handled in the same way.

With Promise objects, you can express asynchronous operations as synchronized operations, avoiding layers of nested callbacks. In addition, Promise objects provide a uniform interface that makes it easier to control asynchronous operations.

But Promise also has some disadvantages, such as:

  • One: can’t cancelPromiseOnce created, it will be executed immediately and cannot be canceled midway;
  • Second: if the callback function is not set,PromiseErrors thrown internally are not reflected externally.
  • Third: when inPendingThere is no way to know what stage you are in (just started or close to completion).

69. Differences between browser feature detection, feature inference and browser UA string sniffing

  • Feature checking is more appropriate for browsers that implement specific features.
  • UAStrings can be modified at will by the browser manufacturer, so they give users a shaky feeling.

70. The understanding of the Function. The prototype. The bind

The function.prototype.bind method creates a new Function. When the new Function is called, its this value is the first argument passed to bind(). Its arguments are the other arguments of bind() and its original arguments.

71. Keep updating ingπŸ€πŸ€

⏳ ⏳

.

Write in the last

About javascript part of the collation, first collation here, the future will continue to update. The development performance optimization article is still in preparation, but due to the recent project burden, it may be delayed (life is not easy and cherish 🌻🌻).

In the process of sorting out, it is inevitable that there will be omissions. If you see mistakes or need to add knowledge points, please leave a message πŸ’ŒπŸ’Œ.