What is a closure? What do closures do?

var a=1;
function  (){
    a++;
    return a;
}Copy the code

A variable, a function, can access variables in a function, and that’s called a closure, which means that if a function refers to a variable other than its own internal variable, the external variable and the function form a closure.

Closures are used to read variables inside a function from outside and keep them in memory at all times:

function  fn1(n){
    return function fn2() {return n++;
    }
}
var fn3=fn1(1);
fn3()//1
fn3()//2Copy the code

Closures allow internal variables to remember the result of the last operation and not be collected by the browser’s garbage collection mechanism because they were not directly referenced.

Closures can also be used to encapsulate an object’s private properties and methods:

function  fn1(n){
    return function fn2() {returnn++; } } var fn3=fn1(1); fn3()//1 var fn4=fn1(2); Fn4 ()//2 //fn3 and fn4 do not affect each other and return different valuesCopy the code

2, What are the uses of call, apply and bind?

Similarity: The first argument accepted is this, which can change the direction of this. Difference: the call can accept the second, third, the first N parameters, apply to accept the second parameter is an array, the bind and the parameters of the call can be accepted, but the return value is a function of the bind, that is even if the parameters in will not executed immediately, need to perform a function called again in order to be true.

var obj = {
    name: 'Lim',
    age:'18'
}

function printName(gender,school) {
    console.log(this.name+this.age+gender+school)
}

printName.call(obj,'man'.'BBC');
printName.apply(obj,['woman'.'BBC']);
printName.bind(obj,'man'.'ORC') ();Copy the code

3. Several commonly used HTTP status codes

Status code 200 indicates the request successful status code 202 indicates the server receives the request status code 301 indicates the requested resource has permanently moved to a new location status code 302 indicates the requested resource temporarily can not access, can visit again status code 400 indicates grammatical errors exist in the request message status code 404 indicates the request fails, The requested resource was not found on the server Status code 500 indicates a server error status code 502 indicates an invalid response from the upstream server when a server working as a gateway or proxy tries to execute the request

Write out an HTTP request and response

The common FORMAT of HTTP requests is divided into four parts: Part 1: Request mode (GET/POST) Path (/ PATH) Protocol/Version (HTTP/1.1)

Part 2: Key: Value pairs

Part three: Carriage return

Part FOUR: Requested data

1 POST /path HTTP/1.1
2 Host:www.baidu.com
2 Content-Length: 24
2 Content-Type: application/x-www-form-urlencoded
3 
4 username=ff&password=123Copy the code

Common HTTP response formats are divided into four parts:

Part 1: Protocol/Version (HTTP/1.1) Status Code Description of the status code

Part 2: Key: Value pairs

Part three: Carriage return

Part 4: Response data (the Content format of this part depends on the Content-Type of Part 2)

1 HTTP/1.1 200 OK 2 Content-length: 200 2 Content-type: text/ HTML 3 4 < HTML >... </html>Copy the code

5. What happens when a page is loaded from the input URL to the display?

5-1.DNS resolution: The browser searches for the IP address based on the domain name in the URL. 5-2.TCP connection: The browser initiates a TCP connection to the server based on the IP address, generating a three-way handshake: (1) The browser initiates a connection request to the server. (2) The server responds to the request and approves the connection. 5-3. Sending an HTTP request: After establishing a connection, the browser sends an HTTP request, including the request line, request header, and request data. 5-4. The server processes the request and returns the response content 5-5. Browser renders the page: the browser receives the response and starts to parse the rendered page. It first parses the HTML to build a DOM tree, then parses the CSS to build a rule tree, and then draws the page according to the tree. 5-6. Close or keep the connection open

6, how to implement array deduplication?

Suppose you have an array array = [1,5,2,3,4,2,3,1,3,4] and you write a function unique that gives unique(array) the value of [1,5,2,3,4].

Requirements:

  1. Don’t do multiple loops, only iterate once
  2. Please give two solutions, one can run in ES 5 environment, one can run in ES 6 environment.

ES5:

Var array =,5,2,3,4,2,3,1,3,4 [1];function unique(arr){
    var newArray = [];
    var hasharr={};
    for (var i = 0; i < arr.length; i++) {
        if(hasharr[arr[i] ]===undefined) { newArray.push(arr[i]); hasharr[arr[i]]=1; }}return newArray;
}
unique(array);
Copy the code

ES6:

Var array =,5,2,3,4,2,3,1,3,4 [1];function unique(arr){
  return Array.from(new Set(arr));
}
unique(array);Copy the code

7. What is the relationship between JSON and JavaScript? What are the differences between JSON and JavaScript?

Relationship: JSON is a language borrowed from JavaScript and a format for data interaction. JSON is a subset of JavaScript (or a subset of JavaScript syntax borrowed from JSON, without adding any original syntax)

Differences: JSON does not support functions, undefined, variables, references, and single quotation marks. Strings and keys of objects do not support single or no quotation marks. There is no built-in Date, Math, or RegExp. JavaScript supports it all.

What is JSONP?

JSONP is a way to request data across domains. The principle is to create script labels dynamically and use script to send requests that are not restricted by the same origin policy. The implementation process is as follows: 1. The requestor, the browser, creates a script tag on the page pointing to the response address and passes a query parameter callback= function name, which can define its own procedure for handling the parameter 2. Responder to get their query parameters according to the front page, create a shape, such as: the function name. Call (” undefined “, {key: value, the key: value,… ({}) or the function name is the key: value, the key: value,… }). 3. The browser receives the response, calls a function, and processes the received data in its own way

9. Why doesn’t JSONP support POST

Because the principle of JSONP is to dynamically create script tags, using the feature that script send requests are not restricted by the same origin policy to achieve cross-domain request data, and dynamically created Script tags can only send GET requests, but do not support POST.

10. What kind of tags can I request?

Form can send POST and GET requests and refresh or open a new page. A can only send get, which refreshes or opens a new page. Img can only be sent as GET and can only be displayed as an image. Link can only be sent as get, which can only be sent as CSS or Favicon. Script can only be issued as get, must be placed in the page, but can only be run as a script.

11. What is front-end MVC?

Model(Model)– View –Controller(Controller) MVC is a regular code specification, which combs the code according to the three-tier structure, making it more clear and easy to understand, specifically: Model data management, including data logic, data requests, data storage and other functions. The front-end Model is mainly responsible for AJAX requests or the LocalStorage storage View is responsible for the user interface, and the front-end View is mainly responsible for HTML rendering. The Controller handles the View events and updates the Model; It also listens for changes to the Model and updates the View, and the Controller controls everything else. Process: The user operates at the view layer, and then the controller monitors the operation of the view layer and requests to the model layer to invoke data. The model layer receives the request and sends the request to the server to invoke data. The server responds to the data to the model layer, and the model layer returns the data to the controller, and the controller updates the data of the view layer.

// M:1. Initialize data 2. Obtain data 3.function(){},
    getData:function(){},
    saveData:function(){},} var view={init() {},
    template: ' '}// C:1. Initialize the view and model, and some events. 2. Var Controller ={init:function(){},
    showData:function() {},bindEvents:function(){},
}Copy the code

How to simulate a class with functions in ES5?

functionPerson(options){// You can add different private attributes this.name=name this.age=age... } // Set the Person class's public property person.prototype. walk=function(){console.log('walk')}
Person.prototype.gender="woman"

var person1=new Person({name:'hi',age:'18'})Copy the code

13. How do I use Promise?

window.myFunction=function(options){
    return new Promise(function(resolve,reject){
        if(success){
            resolve.call(this,responseText)
        }else{
            reject.call(this,errorText)
        }
    })
}

window.myFunction(options).then(
    (responseText)=>console.log(responseText),//resolve
    (errorText)=>console.log(errorText)//reject
)Copy the code

14. Write an AJAX request using native JS (XMLHttpRequest must appear in the code)

let  request=new XMLHttpRequest();
request.open('GET'.'/path');
request.send();
request.onreadystatechange=function() {if(request.readyState===4){
        if(request.status>=200&&request.status<300){
            console.log('success');
        }else if(request.status>=400){
            console.log('failed'); }}}Copy the code

15. About cookies, sessions, and Localstorage

The relationship between cookies and sessions: Generally speaking, sessions are implemented based on cookies

Cookie and Localstorage difference: cookie will be brought to the server every time, to each page, but Localstorage will not, has nothing to do with HTTP, is only stored in the local cookie generally maximum 4K or so, Localstorage maximum 5MB with the browser

Localstorage and sessionStorage: sessionStorage will be invalid after the user closes the page, that is, after the Session (Session) ends, Localstorage will be permanently valid as long as the user does not actively clean the cache

Expries and cache-control Expries is the old way, Expires means when does it expire, cache-control means how long does it expire, expires means when is the user’s local time, and if the user’s local time is out of order it’s a problem, so cache-control is preferred

The difference between ETAG and cache-control is that cache-control does not request information directly, while ETAG requests information but does not download information