Summary of front-end interview questions (theory part 3)

Order of Dom event flow? What is event delegation?

When an element on the page is clicked, the element is captured layer by layer from the document down. Then it bubbles upwards, triggering layer by layer.

Event delegation is to write the event on the parent element, and e.target is the smallest element when the event is captured, that is, the selected element. So you can operate the selected elements according to e.target. In this way, there is no need to bind events to each child element, and the code is more concise.

Event proxy/event delegation

  1. Event bubbling in js We know that events on child elements will bubble up to parent elements.
  2. Event proxy is the event that should have been added to the child element, but we added the event to its parent.
  3. Then there is a problem: with so many child elements at the parent level, how to distinguish which child element the event should belong to?
  4. The answer is: the "event source" is recorded in the event object, which is the sub-element where the event occurs.
  5. It has compatibility issues. Under the old IE, the event source is window.event.srcElement, and other browsers are event.target
  6. What are the benefits of using event delegation?
  7. The first advantage is high efficiency, for example, there is no need to add events to child elements in a for loop
  8. The second advantage is that the new child elements generated by js do not need to add new events to them, which is more convenient in program logic

Closure

A closure is a function that has access to variables in the scope of another function.
MDN says this: a closure is a special kind of object.
A closure's scope chain includes its own scope, the enclosing function's scope, and the global scope. A Note on Closures
Normally, the scope of a function and all its variables are destroyed when the function finishes executing. However, after a closure is created, the scope of this function will remain until the closure no longer exists.
We first know that closures have 3 characteristics :


① Function nested function
② Functions can refer to parameters and variables outside the function
③ Parameters and variables will not be recycled by the garbage collection mechanism

advantage:

①Protect the security of variables in the function, realize encapsulation, and prevent variables from flowing into other environments and cause naming conflicts ②Maintain
a variable in memory, which can be used as a cache (but using too much is also a disadvantage, consuming memory)
③Anonymous self-executing functions can Reduce memory consumption
The disadvantage of closures is that resident memory will increase memory usage, and improper use can easily cause memory leaks.
If you don't need closures for some special task, it's unwise to create functions inside other functions that don't have to, because closures have a negative impact on script performance, including processing speed and memory consumption.

deep copy and shallow copy

The levels of copying are different. Deep copying means that changes in each layer of data will not affect the original object and the new object. In shallow copying, only the changes in the attributes of the first layer do not affect each other, and the changes in deep data will also affect each other.

Shallow copy: Object.assign
Deep copy: JSON.stringify and JSON.parse
2. Disadvantages of JSON stringify and parse processing?

If there is an attribute in the object that is function or undefined, it will be filtered out after processing;
if the attribute value is an object, and the instance object generated by the constructor, the constructor of the object will be discarded;
3. $.extend()

Using the extend method of jquey can not only realize deep copy, but also realize deep merge. specific usage

Deep copy: $.extend({},targetObject) // targetObject is the object to be copied

Deep merge: $.extend(true,{},targetObject1,targetObject2) // You can merge two objects deeply and then return a new object

diff algorithm

The diff algorithm can be regarded as a comparison algorithm, which compares the old and new virtual DOM of the object. As the name suggests, the diff algorithm can find the difference between the old and new virtual DOM, but the diff algorithm not only updates your old and new virtual DOM, but also updates the real DOM according to the comparison results.

The role of the key? What will happen if the key is missing or repeated?

1. The function of the key is mainly to more efficiently compare whether a certain node in the virtual DOM is the same node, realize efficient update of the virtual DOM, and improve performance.

2. It is a necessary condition for Vue to judge whether two nodes are the same node key during the patch process. When rendering a set of lists, the key is often the only identifier, so if the key is not defined, Vue can only think that the two nodes compared are The same one, even if they are not, which leads to frequent updating of elements, making the whole patch process relatively inefficient and affecting performance.

3. In actual use, the key must be set when rendering a set of lists, and it must be a unique identifier. You should avoid using the array index as the key, which may lead to some hidden bugs; The purpose of using the key attribute is also to allow Vue to distinguish them, otherwise Vue will only replace its internal attributes without triggering the transition effect.

4. It can be known from the source code that when Vue judges whether two nodes are the same, it mainly judges the key and element type of the two nodes. Therefore, if it is not set, its value is undefined, and it may always be regarded as two identical nodes. You can only do update operations, which causes a lot of DOM update operations, which is obviously not advisable.

Duplicate keys will cause rendering errors

The role of key in Vue

key The special properties of are mainly used in Vue's virtual DOM algorithm  nodes to identify when comparing  old and new VNodes. If not used  key, Vue uses an algorithm that minimizes dynamic elements and tries to fix/reuse elements of the same type as much as possible. Using  key, it will  key rearrange the order of elements based on changes in and will remove  key elements that don't exist.

Child elements with the same parent element must have unique  key. Repeated ones  key will cause rendering errors.

Insert an element into an array position

  1. Do not use key:
    After the data is inserted, all subsequent different data must be replaced, and finally the data needs to be inserted once
  2. Use key:
    compare, if the value is the same, do nothing, just do an insert operation

If there is no key, compare the new and old tags to be the same, and the tags will be the same, it will be judged to be the same, and the forced update will be replaced

What are closures? pros and cons? How to solve the disadvantages?

What is a closure: In JS, the inner function can access the variables of the outer function, and the outer function cannot manipulate the characteristics of the variables of the memory function. We call this feature closures.

Benefits of closures:

Isolate the scope and protect private variables; with closures, there are local variables, otherwise they are all global variables.
Allows us to use callbacks to operate inside other functions;
variables reside in memory for a long time and will not be recycled by the memory recycling mechanism, that is, to extend the life cycle of variables;
disadvantages of closures: inner functions refer to outer function variables, inner functions used internal memory. If the memory is not released, if there are too many, it is easy to cause a memory leak.

Solution: If the account cannot be canceled automatically, it should be recovered manually in time, and the reference of the function will be assigned null after use.

new features of es6

1. let and const
let means to declare variables. const means to declare a constant.
Once a constant is defined, it cannot be changed. Except for the object, because the address pointed to by the object has not changed.
const must be assigned a value when it is declared.
Both are block scoped.
2. Template string
3. Deconstruction
4. Default value of function
5. Spread / Rest operator, three dots...
6. Arrow function
7. For of for
of traverses the value in the key-value pair
for in traverses Key in the key-value pair
8, class class, syntactic sugar representation of the prototype chain
9, import and export
import improt
export export default
10, promise
Promise is used to handle asynchronous requests more elegantly.
11. Async/await
solves callback hell better than promise
12. Symbol, a new basic type
13. Set collection
stores any type of unique value, that is, the elements saved in the collection are not repeated. Array-like structure.
let arrNew = new Set (array to be deduplicated)

 Understanding of the prototype chain 

js implements object-oriented through prototype chain simulation. For example, by instantiating a constructor, each object can be mounted with its own exclusive properties, and by assigning a method to the prototype of the class, it is a method shared by all objects. The method on the prototype chain is no longer assigned every time it is instantiated

  1. this
     

this refers to the object that calls the function,
this cannot know who it represents before it runs; the this point of js is uncertain; it
has nothing to do with the definition, but has something to do with execution. When executing, who is in front of the point, this is who;
The this in the self-executing function represents the window
when the timer is written, and the window can be omitted; when the timer is executed, the this in it also represents the window;
this is a keyword of js, depending on the use of the function, The value of this changes.
If there is a new keyword, this points to the new object
In the event, this points to the object that triggered the event

What does the new operator in js mainly do?

Create an empty object, and the this variable refers to the object, and at the same time inherits the prototype of the function Properties
and methods are added to the object referenced by this The
newly created object this references, and finally returns this implicitly

what is scope

Concept: The range in which code (variables) can be used is the scope. Mainly to improve the reliability of the program, but also to reduce naming conflicts
Global scope and local scope
Global scope: refers to the entire js file, global variables defined in the global, can be used in the local scope, inside the function Variables that do not declare direct assignment are also called global variables
Local scope: mainly refers to the scope
of the function, which is also the local scope inside the function. Variables defined by var inside the function are called local variables, and local variables cannot be obtained externally.

What is event bubbling? How to stop event bubbling?

Concept: When we click on the child element to trigger the event of the parent element, this phenomenon is called event bubbling, that is, it is propagated from the child element to the ancestor element, just like the bubble floats from the bottom of the water event.stopPropagation(); prevents the event from
bubbling

 Order of Dom event flow? What is event delegation?

When an element on the page is clicked, the element is captured layer by layer from the document down. Then it bubbles upwards, triggering layer by layer.

Event delegation is to write the event on the parent element, and e.target is the smallest element when the event is captured, that is, the selected element. So you can operate the selected elements according to e.target. In this way, there is no need to bind events to each child element, and the code is more concise.

Event delegation principle:  Do not set event listeners for each child node separately, but set the event listener on its parent node, and then use the bubbling principle to affect the setting of each child node

async、await

async is a function that executes asynchronously and implicitly returns a Promise as the result. It is the syntactic sugar of the Generator function, and the Generator function has been improved.

Improve:

  • Built-in executor, no need to manually execute the next() method.
  • better semantics
  • Wider applicability: The co module agrees that the yield command can only be followed by Thunk functions or Promise objects, while the await command of async functions can be followed by Promise objects and primitive types of values ​​(numbers, strings, and Boolean values, but this will be automatically converted into an immediately resolved Promise object).
  • The return value is Promise, which is more convenient than the Iterator object returned by the Generator function, and can be called directly using the then() method.
  • async implicitly returns Promise as a result function, so it can be simply understood that when the function behind await is executed, await will generate a microtask (Promise.then is a microtask).

Async await implementation principle:

When an async function is called, a Promise object (key) may be returned
in the async function. There may be an await expression in the async function. The await expression will cause the async function to suspend execution until the Promise in the expression is resolved and continue to execute after the await in async code and returns the result.
Since the Promise object is returned, its return value cannot be obtained directly at the outermost layer, then the original method can definitely be used: then() chain to process this Promise object Principle
:
The async/await function is actually a syntactic sugar
async/ Await is implemented based on promise. The async function actually wraps promise. The
return value of await is a Promise object. It just puts the code behind await into Promise.then()

The difference between async await and promise
The exception that occurs in async/await cannot be caught. Try/catch is needed to catch the exception.
If any promise object behind await becomes reject, the whole async will be interrupted. If
async await is used, catch can handle it JSON.parse error
 

// 当调用一个 async 函数时,会返回一个 Promise 对象 (关键)
// async/await 出现的异常是无法捕获的,需要借助 try/catch 来捕获异常
function sleep(flag) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(flag){
                resolve('success')
            }else{
                reject('Error')
            }
        }, 2000)
    })
}

// async await 的用法
async function fn(flag) {
    try {
        let result = await sleep(flag)
        return result
    } catch (err) {
        return err
    }
}
// 返回的 a,b 是一个 promise 对象
var a = fn(true)
var b = fn(false)
a.then((res)=>{
    console.log(res) // success
})
b.then((res)=>{
    console.log(res) // Error
})

Guess you like

Origin blog.csdn.net/Holly31/article/details/130740903