What is a closure? What are closures used for? What are the disadvantages of closures?

What is a closure: Closures, also known as function closures, bind to the surrounding environment through a function that retrieves the values of surrounding variables. What closures are for: Prior to ES6, JavaScript variables existed as var, and if a var was a global variable, it could also be read inside a function. Local variables inside a function cannot be read outside the function. So by redefining a subfunction inside a function and returning it, you can get the variables inside the function through that subfunction, which is called a closure.

function test(){
    let testValue = 1;
    function testClosure(){
        return testValue;
    }
    return testClosure;
}

let a = test();
console.log(a());
Copy the code

As shown above, the variable testValue inside test is obtained through testClosure(), the closure of the function test(). What are the disadvantages of closures? In this code, test() is assigned to a global variable, a, so test() and its contained functions and variables are resident in memory and not cleaned up by garbage collection after the call. Closures consume a lot of memory and need to be cleaned manually for performance and security reasons to prevent memory leaks. If the parent function = object, the closure =public method, and the inner variable =private variable, then the internal and external variables can be manipulated by the closure, which can be misleading.

What are the uses of ‘call’, ‘apply’ and ‘bind’?

To understand call, apply, and bind, you first need to understand this\

this

This principle of reference: (JavaScript) [www.ruanyifeng.com/blog/2018/0]…

var obj = {
  foo: function () { console.log(this.bar) },
  bar: 1
};

var foo = obj.foo;
var bar = 2;

obj.foo() / / 1
foo() / / 2
Copy the code

This is inside the function body and refers to the context in which the function is executed. The runtime environment of obj.foo() points to obj, and the runtime environment of foo() points to the current global environment, which is window. Bar is found in the window property.

There are typically four call modes for this: function call mode, method call mode, constructor call mode, and Call /apply call mode.

Function call pattern

The function call pattern calls the function directly after using this in the function:

function f1(){
    console.log(this);
}
f1();
Copy the code

The context to which this points is Window

Method invocation pattern

In object-oriented programming, the Method Invocation Pattern is called Method when the Function is an object attribute. This is bound to the corresponding object when the method is called. When a function is stored as a method of an object, if the calling expression contains an action to extract a property, it is called as a method, and this is bound to the object.

let a = 1;
let obj = {
    a:2.f2: function(){
        console.log(this.a);
    }
}
obj.f2();
Copy the code

The print result is 2. Obj.f2 () means that F2 () is bound to OBj, and the context of F2 () is the internal environment of OBJ. Therefore, obj.f2() is equivalent to obj.f2().call(obj)

Constructor invoke pattern

Characteristics of the constructor call pattern:

  1. Constructors usually start with a capital letter
  2. General and keywordnewUsed together
  3. ConstructorthisPoint to thenewKeyword to create an instance object
  4. The default returnnewThe created object (this)

When you new a function, you actually create a new object attached to the Prototype member, and this is bound to that new instance object.

function Person(name,age){
// This refers to instances
    this.name = name;
    this.age = age;
    this.getAge = function(){
        console.log(this.age); }}var person = new Person('Alice,1);
person.getAge();
Copy the code

The print result is 1.

call(), apply(), bind()

Call (), apply()

Call () and apply() are very close. Call is the syntactic sugar of bind, used to specify this and pass arguments to functions. The only difference is that they accept different types of arguments.

call(this, args, args, ...) ; apply(this, [argsArray]);
Copy the code

Call () takes several arguments in addition to the specified this. The apply () accepts a specified this, accepting only in the form of an array parameter If this = undefined | | null, this points to the window

Use the bind ()

The bind method directly changes the this pointer to the function and returns a new function. This is the first argument to the bind binding whenever the function is called again. The second argument to bind starts with a list of arguments passed in, and is often used to specify default arguments for functions.

let alice = {
    name: 'alice'.age: 1
}
function Person(name, age){
    console.log(`this: The ${this.name} The ${this.age}`);
    console.log(`default: ${name} ${age}`);
    console.log(arguments)}let test = Person.bind(alice,'Bob'.2);
test('third one'.3);
Copy the code

The results are as follows

This: Alice 1 default: Bob 2 Arguments(4) ["Bob", 2, "third one", 3, callee: ƒ, Symbol(symbol.iterator): ƒ]Copy the code

Name at least 10 HTTP status codes and describe their meanings.

Responses fall into five categories: message response (100-199), success response (200-299), redirect (300-399), client error (400-499), and server error (500-599).

100 Continue:

Temporary response. The client should continue to request

200 Ok:

The request succeeded. The four methods of HTTP have four meanings

206 Partial Content:

Partial success. Some OF the GET requests were successfully processed. It is mainly used to realize breakpoint continuation or large file transfer, and can also be used for segmented video transmission. Range must be included in the request to indicate the Range of files to request.

301 Moved Permanently:

Permanently move. The requested resource has been permanently moved to the new location. This status code indicates that the requested URI resource path has changed and that the new URL will be found in the Location: header field of the response. It is best to use 301 when dealing with GET or HEAD methods.

308 Permanent Redirect:

Permanent redirection. The semantics are the same as 301, but the user cannot change the HTTP method used.

302 Found:

Temporary redirection. The requested URI resource path changed temporarily and may continue to change. Therefore, the client must continue to use the URI for future access. The new URL will be found in the Location: header field of the response.

400 Bad Request:

Incorrect request. The server could not understand the request, the semantics or parameters were wrong.

403 Forbidden:

Access is prohibited. The server understands the request but refuses to execute it, and the client has no right to access the requested content.

404 Not Found:

The request failed. The server could not find the requested content.

502 Bad Gateway:

Gateway error. The server received an incorrect HTTP response from the upstream server.

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].

Write two answers:

  1. An answer not implemented with Set (6 points)
  2. Another answer uses Set (4 marks)
  3. (Additional points) If Map/WeakMap is used to support object weight removal, an additional 5 points will be added.
  4. Add 2 points for each option if you say what’s wrong with each option.
The Map to heavy

A Map is similar to a dictionary in other languages. It consists of [key] values, and keys cannot be repeated. Check whether the key already exists by using the has() method.

// Use Map
function unique(array){
    let map = new Map(a);let unique_array = new Array(a);for(let i=0; i<array.length; i++){
        if(map.has(array[i]) === false){
        map.set(array[i], true); unique_array.push(array[i]); }}return unique_array;
}
console.log(unique([1.5.2.3.4.2.3.1.3.4]));
Copy the code
Set to heavy

A Set has only a key, and the key cannot be repeated.

// Use Set()
function unique(array){
    return Array.from(new Set(array));
}
console.log(unique([1.5.2.3.4.2.3.1.3.4]));
Copy the code
disadvantages

Both Set and Map are new data structures in ES6. Although the syntax is simple and efficient, they cannot be used in ES6 before, causing compatibility problems. Objects cannot be used as keys, so neither sets nor maps can perform object deduplicating.

Reference: lequ7.com/JavaScript-… Juejin. Cn/post / 684490…

DOM event correlation

  1. What is event delegation? Four points
  2. How do I block the default action? Three points
  3. How do I stop events from bubbling up? Three points

Juejin. Cn/post / 695578…

How do you understand JS inheritance?

  1. 5 points for prototype-based inheritance
  2. 5 points for class-based inheritance

Unlike Java or C++, class and extends in JavaScript count as syntactic sugar. JS doesn’t really implement class, and everything about inheritance is still based on the prototype chain.

JavaScript has only one structure: objects. Each object has a private __proto__ attribute that points to its constructor’s Prototype. Each constructor’s __proto__ refers to the prototype of its parent constructor.

The ES6 extends substance completes the __proto__ and Prototype points of each object and constructor, making up the prototype chain.

Super is the equivalent of call() and bind(), passing attributes of the parent constructor to subclasses.

Sort an array

Give an array of positive integers array = [2,1,5,3,8,4,9,5] write a function sort that causes sort(array) to be sorted from smallest to largest. It can also be completely new memory.

Do not use the built-in SORT API of JS

function mergeSort(arr){
    let len = arr.length;
    if(len < 2) {return arr;
    }
    let left = arr.slice(0.Math.floor(len/2));
    let right = arr.slice(Math.floor(len/2),len);
    return merge(mergeSort(left),mergeSort(right))
}
function merge(left,right){
    if(left.length === 0) {return right;
    }
    if(right.length === 0) {return left;
    }
    return left[0] > right[0]? [right[0]].concat(merge(left,right.slice(1))) : [left[0]].concat(merge(left.slice(1),right))
}
numbers =  [2.1.5.3.8.4.9.5]
console.log(mergeSort(numbers));
Copy the code

What do you know about Promise?

Answer key points:

  1. The purpose of the Promise
  2. How do I create a New Promise
  3. How to use promise.prototype.then (MDN)
  4. How to use promise.all (MDN)
  5. How to use promise.race (MDN)

Juejin. Cn/post / 698733…

Talk about cross-domains.

Key points:

  1. What is homology
  2. What is cross-domain
  3. The json cross-domain
  4. CORS cross-domain

Juejin. Cn/post / 698761…

Understanding the front end

The distinction between front and back ends should come from the idea of separating front and back ends. To the user, the “front end” represents all parts of the software that can be seen, understood, and manipulated, while the “back end” supports and processes the information provided and fed back by the front end. For developers, the narrow front end refers only to the Web front end, the world constructed by HTML + CSS + JS. And now there is the concept of the big front end, including the website, Android client, iOS client and wechat small programs. One-shot development, solving problems through cross-platform technologies, requires a high level of knowledge, but is a more promising way out of the box. No matter which technology is used, the essence of the front end is to achieve human-computer interaction and facilitate users to read, understand and use the various functions of software and hardware. It is safe to simply implement as designed, but incorporating an understanding of interaction and security into the implementation process may reduce many future problems. Front-end engineers need not only the ability to write code, but also basic UI design knowledge, basic usable security knowledge, and some back-end and database related experience, so as to locate and solve problems faster.