Front-end interview

Front-end interview

1. Different variable declarations: const and let

let means declaring a variable, and const means declaring a constant, both of which are block-level scopes. Variables declared by const will be regarded as constants, which means that its value cannot be modified after it is set.

If const is an object, the value of the object can be modified, and the reference address cannot be changed

2.String template''

3. Arrow function

Arrow function is simply a function of the form, he does not need to create a function keyword, you can omit the return keyword, and he inherited the context of this keyword copy the code

4.The difference between call, apply, bind

bind: He will not call it immediately, but return a bound new function

Function.prototype.myBind = function(context){ //Type judgment if(typeof this !=='function'){ throw new TypeError('must be a function') } let self = this//This this is the function that calls bind let argsArr = [...arguments].slice(1) return function(){ let bindFuncArg = [...arguments]//Combine the two passed parameters let totalArgs = argsArr.concat(bindFuncArg) return self.apply(context, totalArgs) }} Copy code

call: call immediately, return the result of the function execution, this. points to the first parameter, there may be multiple parameters behind, and these parameters are the parameters of the function

Function.prototype.myCall = function(thisObj = window){ thisObj.fn = this//here this refers to the function that calls myCall //Process arguments let arg = [...arguments].slice(1) let result = thisObj.fn(...arg)//execute the function delete thisObj.fn return result } Copy code

apply: call immediately, return the execution result of the function, the first parameter is the execution of this, the second parameter is an array, and the contents of the array are the parameters of the function

Function.prototype.myApply = function (context = window, arr){ context.fn = this let result if(!arr){ result = context.fn() } else { result = context.fn(...arr) } delete context.fn return result } Copy code

5. A complete vue life cycle will go through the following hook functions

It is the first hook triggered after new Vue(). In the current stage, data and methods on data, methods, computed, and watch cannot be accessed.

Occurs after the instance creation is completed, the current stage has completed the data observation, that is, the data can be used, and the data can be changed. Changing the data here will not trigger the updated function. You can do some initial data acquisition, and you cannot interact with the Dom at the current stage. If you have to, you can access the Dom through vm.$nextTick.

Occurs before mounting, before the template template has been imported into the rendering function to compile. At the current stage, the virtual Dom has been created, and rendering will begin soon. You can also make changes to the data at this time without triggering updated.

Occurs after the mounting is completed. At the current stage, the real Dom is mounted, the data is two-way bound, and the Dom node can be accessed, and the Dom can be operated using the $refs attribute.

It happens before the update, that is, the responsive data is updated, and the virtual dom is triggered before the re-rendering. You can change the data in the current stage without causing re-rendering.

Occurs after the update is completed, the current stage component Dom has been updated. It is important to avoid changing the data during this period, as this may cause an endless loop of updates.

It happens before the instance is destroyed, and the instance can be used in the current stage, and we can do the finishing touches at this time, such as clearing the timer.

After the instance is destroyed, only the dom shell is left at this time. The component has been disassembled, the data binding has been removed, the monitor has been removed, and all sub-instances have been destroyed

6. What are the 5 core attributes of Vuex?

  1. state vuex uses a single state tree, which contains all application-level states with one object
  2. Getters are equivalent to computed calculated properties in vue
  3. The only way for mutations to change the state of the state in vuex is to submit the mutation!
  4. actionsaction submits a mutation instead of directly changing the state, an action can contain any asynchronous operation
  5. Modularization of modules.

7. How to use Vuex state in batches in components?

Use the mapState helper function and use the object expansion operator to mix state into the computed object

8. Can you talk about MVVM?


evolve into
. The Model layer represents the data model, the View represents the UI component, and the ViewModel is the bridge between the View and Model layers. Data will be bound to the viewModel layer and automatically rendered to the page. When the view changes, the viewModel layer will be notified to update the data.

9. Do you know nextTick, what is the implementation principle?

We can understand that Vue is executed asynchronously when updating the DOM. When the data changes, Vue will open an asynchronous update queue, and the view needs to wait for all the data changes in the queue to be completed, and then update uniformly.

10. Talk about Computed and Watch

The essence is a watcher with a cache, and the view is updated when the dependent properties change. It is suitable for computing scenarios that consume more performance. When the expression is too complex, putting too much logic in the template will make the template difficult to maintain. You can put the complex logic in the calculated attributes for processing.

Without caching, it is more of an observation function, which can monitor certain data to execute callbacks. When we need to deeply monitor the properties in the object, we can open
deep: true
Option, so that every item in the object will be monitored. This will cause performance problems, you can use it for optimization
String form
Monitor, if it is not written in the component, don't forget to use
unWatch manual logout

11. Tell me about the principle of v-model? How to realize v-model

The essence is syntactic sugar, which can be seen as
value + input
Syntactic sugar for methods. Can pass the model attribute
Properties to customize. The native v-model will generate different events and attributes according to different tags

12. What are the ways of component communication

Father -> Son

, Son -> father
$on, $emit

Brother component communication

Bus the Event `cross-component communication` Vue.prototype. $ = Bus new new Vue duplicated code

Cross-level component communication


13. Life cycle call sequence

The calling sequence of the components is

Father and son
, The order of rendering completion is
Son before father

The destruction operation of the component is

Father and son
, The order of completion of destruction is
Son before father

Load the rendering process
Parent beforeCreate-> Parent created-> Parent beforeMount-> sub beforeCreate-> sub created-> sub beforeMount-> sub mounted-> Parent mounted copy the code
Sub-component update process
Father beforeUpdate-> child beforeUpdate-> child updated-> Father updated copy the code
Parent component update process
Father beforeUpdate -> parent updated copy the code
Destruction process
Father beforeDestroy-> child beforeDestroy-> child destroyed-> Father destroyed copy the code

14.Keep-alive understand

Component caching can be implemented, and the current component will not be uninstalled when the component is switched.

15. Let me talk about the role of virtual Dom and key attributes

Because manipulating the DOM in the browser is very expensive. Frequent manipulation of the DOM will cause certain performance problems. This is the virtual dom


Vue2's Virtual DOM borrows from open source libraries

The realization.

The essence of Virtual DOM is to describe a DOM node with a native JS object. It is an abstraction of the real DOM.
(That is, the VNode class in the source code, which is defined in src/core/vdom/vnode.js.)

The mapping of VirtualDOM to real DOM needs to go through the stages of create, diff, and patch of VNode.

"The role of the key is to reuse DOM elements as much as possible."

Only when the order of the nodes in the new and old children is different, the best operation should be to move the position of the element to achieve the purpose of updating.

The mapping relationship needs to be saved in the nodes of the new and old children, so that reusable nodes can be found in the nodes of the old children. The key is the unique identifier of the node in children

16.Event Loop

Event Loop
Task queue and event loop, execution order: execute current stack -> execute micro task -> push the first one in the macro task queue to the stack for execution, (if you encounter a micro task, put the micro task in the micro task queue )-->Execute micro task-->The second item in the macro task queue is pushed to the stack for execution, and this step of installation loops in turn

The event loop can be simply described as the following four steps:

  1. The function is pushed into the stack. When an asynchronous task is executed in the Stack, it will be thrown to WebAPIs, and then the synchronous task will be executed until the Stack is empty;
  2. During this period, WebAPIs completes the event and puts the callback function into the queue for execution (the micro task is placed in the micro task queue, and the macro task is placed in the macro task queue)
  3. When the execution stack is empty, the Event Loop clears the execution of the microtask queue;
  4. After the micro task queue is emptied, enter the macro task queue, take the first task of the queue and put it into the Stack (stack) for execution, and return to step 1.

17.js simulation of the realization of the new operator

Create an empty simple JavaScript object (ie {}); Link the object (that is, set the object's constructor) to another object; Use the newly created object in step 1 as the context of this; If the function does not return an object, it returns this. function objectFactory(){ var obj = {}; //Get the first parameter of the method (and delete the first parameter), which is the constructor var Constructor = [].shift.apply(arguments); //Point the internal property __proto__ of the new object to the prototype of the constructor, so that the new object can access the properties and methods in the prototype obj.__proto__ = Constructor.prototype; //Get the return value of the constructor var ret = Constructor.apply(obj, arguments); //If the return value is an object, return the object, otherwise return an instance object of the constructor return typeof ret === "object"? ret: obj; } Copy code

18. Briefly introduce the garbage collection mechanism of the V8 engine

The garbage collection mechanism of v8 is based on the generational collection mechanism. This mechanism is based on the generation hypothesis. This hypothesis has two characteristics. One is that newly born objects are prone to die early, and the other is that undead objects will live longer. Based on this hypothesis, the v8 engine divides the memory into the young generation and the old generation.

Newly created objects or objects that have been garbage collected only once are called the new generation. Objects that have experienced multiple garbage collections are called the old generation.

The new generation is divided into two spaces: From and To, and To is generally idle. When the From space is full, the Scavenge algorithm will be executed for garbage collection. When we execute the garbage collection algorithm, the application logic will stop and continue execution after the garbage collection is over. This algorithm is divided into three steps:

  1. First check the surviving objects in the From space. If the object is alive, it is judged whether the object meets the conditions for promotion to the old generation, and if the conditions are met, it is promoted to the old generation. If the condition is not met, move the To space.
  2. If the object is not alive, the space of the object is released.
  3. Finally, the roles of From space and To space are exchanged.

There are two conditions for the promotion of the new generation object to the old generation:

(1) The first one is to judge whether the object has already been scavenged once. If experienced, copy the object from the From space to the old generation; if not, copy it to the To space.

(2) The second is whether the memory usage ratio of the To space exceeds the limit. When an object is copied from the From space to the To space, if the To space usage exceeds 25%, the object is directly promoted to the old generation. The reason for setting 25% is mainly because after the algorithm ends, the two spaces will exchange positions after the end. If the memory of the To space is too small, it will affect the subsequent memory allocation.

The old generation adopted the mark removal method and the mark compression method. The mark removal method first marks the surviving objects in the memory, and removes those unmarked objects after the mark ends. Since the mark is cleared, it will cause a lot of memory fragmentation, which is not convenient for subsequent memory allocation. So to solve the problem of memory fragmentation, a marked compression method is introduced.

Due to the logic of suspending the application during garbage collection, for the new generation method, due to the small memory, each pause will not be too long, but for the old generation, each time the garbage collection will take a long time, and the pause will cause a lot Impact. In order to solve this problem, V8 introduces the method of incremental marking, which divides the process of a pause into multiple steps. Each time a small step is executed, the running logic is executed for a while, and it runs alternately.

19. What operations will cause memory leaks?

1. Unexpected global variables

2. The forgotten timer or callback function

3. Get rid of the DOM reference

4. Closure

The first case is that we accidentally created a global variable due to the use of undeclared variables, and this variable remains in memory and cannot be recycled.

The second case is that we set

Timer, and forget to cancel it. If the loop function has a reference to an external variable, then this variable will remain in the memory and cannot be recycled.

The third situation is that we get a reference to a DOM element, and the latter element is deleted. Since we have kept the reference to this element, it cannot be recycled.

The fourth case is the unreasonable use of closures, resulting in some variables being kept in memory.

20. The life cycle method of React components

componentWillMount **()**-Execute before rendering, both on the client and server.

componentDidMount **()**-Only executed on the client after the first rendering.

componentWillReceiveProps **()**-Called when props are received from the parent class and before calling another renderer.

shouldComponentUpdate **()** returns true or false based on specific conditions. If you want to update the component, please return true otherwise return false . By default, it returns false.

componentWillUpdate **()**-Called before rendering in the DOM.

componentDidUpdate **()**-Called immediately after rendering occurs.

componentWillUnmount **()**-Called after unmounting the component from the DOM. Used for

21. Anti-shake and throttling methods

Anti-shake: It means that the function will be executed after the trigger time is n seconds. If the event is triggered again within n seconds, it will recalculate the execution time
/* func: The function to be processed for anti-shake processing delay: the time to be delayed immediate: Whether to use immediate execution true immediate execution false non-immediate execution */ function debounce(func,delay,immediate){ let timeout;//Timer return function(arguments){ //Determine whether the timer exists, clear it if it exists, and restart the timer count if(timeout) clearTimeout(timeout); //Determine whether it is immediate anti-shake or non-immediate anti-shake if(immediate){//Execute immediately const flag = !timeout;//Here is the negation operation timeout = setTimeout(()=>{ timeout = null; },delay); //The function will be executed immediately after the event is triggered, and then the effect of the function can be continued if the event is not triggered within n seconds. if(flag),arguments); }else{//Non-immediate execution timeout = setTimeout(()=>{,arguments); },delay) } } } Copy code

Throttling: Refers to the trigger time but only executes the function once in n seconds, and during the second time, no matter how many times you click it, it only executes the event once.

function throttle(func,delay){ let prev = 0;//Last record time return function(arguments){ let now =;//Current timestamp if(now-prev> delay){//current time-last time> delay time,arguments);//Execute function to send request prev = now;//Reset recording time } } } Copy code

22. Prototype

The constructor is a special method, mainly used to initialize the object when it is created. Each constructor has a prototype (arrow function and Function.prototype.bind() does not) property, this prototype property is a pointer to an object, the purpose of this object is to contain all instances of a specific type Shared properties and methods, that is, this prototype object is used to share properties and methods with instance objects. The __proto__ of each instance object points to the prototype property of this constructor/class.

23. Prototype chain

This is when we instantiate PersonB to get the instantiated object, and access the properties of the instantiated object will trigger the get method. It will first look for its own properties. If there is no such property, it will look in __proto__, layer by layer Go up until you find the top-level object Object. This search process is the prototype chain.

24. State the process after entering the URL and carriage return

  1. Read cache: Search your own DNS cache. (If the IP address is found in the DNS cache, skip the next step to find the IP address and visit the IP address directly.)
  2. DNS resolution: resolve domain names into IP addresses
  3. TCP connection: TCP three-way handshake, a brief description of the three-way handshake Client: Are you on the server? Server: I am on the client side, do you want to connect to me? Client: Yes, the server, I want to link. The connection is opened, you can start requesting
  4. Send HTTP request
  5. The server processes the request and returns HTTP messages
  6. The browser parses and renders the page
  7. Disconnected: TCP waved four times

About the sixth step, the browser parses and renders the page. If the returned html page parses the DOM tree according to the HTML, generates the CSS rule tree according to the CSS analysis. Combines the DOM tree and the CSS rule tree to generate the render tree. Calculate each node according to the render tree. Draw the page based on the calculated information