2019 front-end interview, interview 100 essences, /js

Li gulare 2020-11-12 23:46:25
front-end end interview interview essences


Most of the following questions are junior and intermediate , The answers are also concise , You can deal with it during the interview , In case there is nothing to say on the first side PASS. If these questions can help you quickly recall what you learned , Connect the skill points before and after , Have a good performance in the interview , It doesn't cost me the heart to organize these interview questions . Last , These answers are for reference only , Don't memorize . May you all find satisfactory jobs .

I'm Li gulare , Zeng Quanzhan Development Engineer , Before today's headlines, front-end architects , Today's start-up company CEO. My official account can get more front-end technology and experience . My life creed sharing is value !

JS piece

Catalog

1.let、var、const difference ?

2. What is functional currification ?

3. What is? Promise object , What are the uses ?

4. How to use Promise Object implementation ajax?

5. What is? REST, What's the use of it ?

6. What is a closure , Let me give you an example

7.promise、generator、async/await How do you use it? , What's the difference? ?

8.apply/call/bind  What's the difference? ?

9. What is variable Promotion 、 Function enhancement ?

10. What is event bubbling , How it works ? How to prevent events from bubbling

11. Simple talk about js Inheritance in

12. frequently-used js What are the array operation methods ?

13.js Array weight removal , It can be realized in several ways ?

14. Array forEach and map The difference between ?

15.jQueryajax 、fetch、 axios What are the similarities and differences , What are the applicable scenarios ?

16.es6 What problems can extension operators solve ?

17. Yeah, yeah js The event loop event loop?

18.Math.min() and Math.max() Size comparison ?

19. How to copy objects in depth ?

20. How to continue file upload by breakpoint ?

21.js How to deal with anti shake and throttle ?

22. Event delegation and its advantages and disadvantages

23. Introduce this All kinds of situations

24.== and === The difference between , When to use equality ==

25. Introduce the prototype chain ( Is the problem of inheritance solved )

26.JS What is the garbage collection mechanism in , What kind is commonly used , How to deal with ?

27.Promise and setTimeout The difference between ?

28. Introduce next breadth first traversal (BFS) And depth first traversal (DFS)?

29.for in and for of The difference between

30.typeof and instanceof difference ?

31. There are several common ways of inheritance


1.let、var、const difference ?

answer :

1.var The declared variables are mounted on the window On , and let and const Declared variables will not

2.var Declaration variable has variable promotion ,let and const No variable promotion

3.let and const Declare chunk scope ,var Variable elevation does not form a scope

4. Under the same scope let and const Cannot declare a variable with the same name , and var Sure

5.var and let You can modify declared variables ,const Can not be

6.const The defined variable must be initialized

7.let、const There is a temporary dead zone

 

2. What is functional currification ?

answer : It belongs to the application of higher order function , Pass some parameters to the function to call the Coriolis function , Let it return a function to handle the rest of the arguments .

// Convert a function that takes multiple arguments to a function that takes a single parameter

// currying

var foo = function(x) {

return function(y) {

return x + y

}

}

foo(3)(4) // 7

// Common method

var add = function(x, y) {

return x + y;

}

add(3, 4) //7

3. What is? Promise object , What are the uses ?

answer :

Promise Object definition

Promise Is a solution to asynchronous programming , It's a container , It holds an event that will end in the future ( This is usually an asynchronous operation ) Result . grammatically ,Promise It's an object , From it you can get messages for asynchronous operations . It can be used to solve “ Back to hell ” The problem of .Promise Provide uniform API, Various asynchronous operations can be handled in the same way .promise An object is a constructor , Used to generate Promise example ;

Promise Characteristics of the object

(1) The state of the object is not affected by the outside world ,promise The object represents an asynchronous operation , There are three states ,pending( Have in hand )、fulfilled( Have succeeded )、rejected( Failed ). Only results of asynchronous operations , You can decide which state you are in , No other operation can change this state , This is also promise The origin of the name “ Chengruo ”;

(2) Once the state changes, it won't change again , You can get that at any time ,promise Object state changes , There are only two possibilities : from pending Turn into fulfilled, from pending Turn into rejected. This is called resolved( Have to finalize the design ). If change has already happened , You again to promise Object to add a callback function , And you'll get that immediately , With the event (event) Completely different , The characteristic of the event is : If you missed it , You can't get results by listening again .

With Promise object , The asynchronous operation can be expressed as a synchronous operation flow , Avoid layers of nested callback functions . Besides ,Promise Objects provide a uniform interface , Makes it easier to control asynchronous operations .

Promise There are also some disadvantages . First , Can't cancel Promise, Once it's created, it's executed immediately , Unable to cancel . secondly , If you do not set the callback function ,Promise An error thrown internally , It doesn't react to the outside . Third , When in pending In the state of , It is impossible to know at what stage ( Just started or almost finished ).

Promise Object usage

It's a constructor , This constructor has two parameters , Namely :resolve( Callback function after success )、reject( Callback function after failure ).

because promise Represents an asynchronous operation , Whenever we new One promise example , It means a specific asynchronous operation , Then the result of this asynchronous operation can only have two states : success / Failure , Both need callback functions resolve/reject return . So after getting the results of the operation internally , Can't use return Return the result of the operation to the caller , In this case, you can only return the success or failure result to the caller in the form of callback function .

 

promise After instance generation , It can be used then Methods specify resolved State and rejected Callback function for state

 

then Method can accept multiple callback functions as parameters , The first callback function is promise The state of the object changes to resolved Called when the , The second callback function is promise The state of the object changes to rejected Called when the , among , The second function is optional , It is not necessary to provide , Both of these functions accept promise Object as a parameter ;

* adopt .then When specifying the callback function , A successful callback function must pass , The callback function can fail .

If the front promise Execution failure , Unknown affects the termination of subsequent operations , Two ways to catch exceptions :

① Can be for each promise Specifies the failure callback ;

function(err){

console.log(……)

})

② Finally add catch(function(err){

console.log(……)

})// It means that if any one of them has reported an error , Report an error immediately , And terminate the following ; If there is no error in the front , The front is executed normally .

4. How to use Promise Object implementation ajax?

 

getJSON It's right XMLHTTPRequest Encapsulation of objects , Used to issue a target for JSON Data HTTP request , And return to a promise object , It should be noted that , stay getJSON Inside ,resolve Functions and reject When a function is called , They all have parameters ;

If the resolve Functions and reject Function with arguments , Then their parameters are passed to the callback function ,reject The arguments to a function are usually Error Instance of object , Indicates the error thrown ,resolve In addition to normal values, the parameters of the function , It could be another promise example ;

 

5. What is? REST, What's the use of it ?

answer :

REST It's a design API The pattern of . The most common data format is JSON. because JSON Can be directly by JavaScript Read , therefore , With JSON formatted REST Style API Simple 、 Easy to read 、 Easy to use features . adopt REST Pattern design API You can put web app All functions are encapsulated , It's easy to separate the front end from the back end , Make the front-end code easy to write , Back end code is easy to test .

6. What is a closure , Let me give you an example

answer :

“ Closures are functions that can read internal variables of other functions . For example, in javascript in , Only subfunctions inside a function can read local variables , So closures can be understood as “ A function defined inside a function “. In essence , Closures are bridges that connect functions inside and outside .”

give an example : The most common way to create closures , It's creating another function inside one function . In the following example closure It's a closure ,

function func(){

vara =1 ,b = 2;

funciton closure(){

return a+b;

}

return closure;

}

 

7.promise、generator、async/await How do you use it? , What's the difference? ?

answer :

We know JavaScript It's a single-threaded language , If you don't have asynchronous programming, you have to get stuck .

before , There are four ways to program asynchronously

Callback function

Event monitoring

Release / subscribe

Promise object

Now it is said that the ultimate solution to asynchronous programming is ——async/await

For a more detailed introduction, please refer to the following article :

https://www.jianshu.com/p/1c9e9c161612

 

8.apply/call/bind  What's the difference? ?

answer :

The function of these three is to change the function runtime this The direction of .

call Method :

grammar :call([thisObj[,arg1[, arg2[, [,.argN]]]]])

Definition : A method that calls an object , Replace the current object with another object .

explain :call Method can be used to call a method instead of another object .call Method to change the object context of a function from its initial context to thisObj New object specified .

If not provided thisObj Parameters , that Global Object is used as thisObj.

apply Method :

grammar :apply([thisObj[,argArray]])

Definition : A method of applying an object , Replace the current object with another object .

explain : If argArray Not a valid array or not arguments object , Then it will lead to a TypeError.

If not provided argArray and thisObj Any parameter , that Global Object will be used as thisObj, And no arguments can be passed .

bind Method :

grammar :bind(thisArg[, arg1[, arg2[, ...]]])

Definition : Transform a function that takes multiple parameters to accept a single parameter .

explain :bind() Of the function returned by the method length( Number of formal parameters ) It is equal to the number of formal parameters of the original function minus the input bind() The number of arguments in the method ( All parameters after the first parameter ), Because of the introduction bind The arguments in are bound to the formal parameters of the original function .

 

9. What is variable Promotion 、 Function enhancement ?

answer :

Variable Promotion :

The short answer is in js The engine precompiles before the code is executed , Variable and function declarations are promoted to the top of their corresponding scopes during precompiling , Variables declared within a function are promoted only to the top level of the function scope .

When a variable defined inside a function is the same as an external variable , Then the variable in the function body will be raised to the top .

for instance :

console.log(a); // undefined

var a = 3;

 

// The precompiled code structure can be seen as the following running sequence

var a; // Put the variable a To the very top , Assignment logic does not elevate .

console.log(a); // undefined

a = 3; // Code execution to the original location, that is, the original assignment logic

 

Function enhancement :

Function promotion will only improve the function declarative writing , There is no function promotion in the writing of function expression .

The priority of function promotion is higher than that of variable promotion , That is, function promotion is above variable promotion .

 

10. What is event bubbling , How it works ? How to prevent events from bubbling

answer :

Trigger some kind of event on an object ( For example, click onclick event ), If this object defines a handler for this event , Then this event will call the handler , If this event handler or event return is not defined true, Then this event will propagate to the parent object of this object , From inside to outside , Until it's dealt with ( All events of the same kind of the parent object will be activated ), Or it reaches the top of the object hierarchy , namely document object ( Some browsers are window)

Several ways to prevent events from bubbling

The first one is : event.stopPropagation();

The second kind : return false;

The third kind of : event.preventDefault();

11. Simple talk about js Inheritance in

answer :

There are six ways

1. Prototype chain inheritance

JavaScript The basic idea of realizing inheritance : Inherit the properties and methods of one reference type from another through prototypes .

2. Inheritance by borrowing the constructor ( Forgery object or classic inheritance )

JavaScript The basic idea of realizing inheritance : Calling a supertype constructor inside a subclass constructor .

By using apply() and call() Method can execute a constructor on a newly created subclass object .

3. Combination inheritance ( Prototype + To borrow construction )( Pseudo classical inheritance )

JavaScript The basic idea of realizing inheritance : Combine the prototype chain with the borrowing constructor technique , So as to give full play to the advantages of the two inheritance patterns .

Combine the prototype chain with the technique of borrowing constructors , In order to take advantage of the advantages of both .

4. Original pattern inheritance

JavaScript The basic idea of realizing inheritance : With prototypes, you can create new objects based on existing objects , You don't have to create a custom type for that .

5. Parasitic inheritance

JavaScript The basic idea of realizing inheritance : Creates a function that simply encapsulates the inheritance process , This function internally enhances the object in some way , Finally, it returns the object as if it did all the work .

Parasitic inheritance is an enhanced version of archetypal inheritance .

6. Parasitic combinatorial inheritance

JavaScript The basic idea of realizing inheritance : Inherit properties by borrowing functions , Methods are inherited through a hybrid form of a prototype chain .

12. frequently-used js What are the array operation methods ?

answer :

1. Array.shift()------ Delete and return the first element

effect : Remove the first element from the array ( That is, the subscript is 0 The elements of ), And return the element .

Be careful :1) After deleting elements , Length of array -1.

2) If the array is empty , that shift() Method will do nothing , return undefined value .

2.Array.pop()------ Delete and return the last element

effect : Remove the last element from the array ( That is, the subscript is length-1 The elements of ), And return the element .

Be careful :1) After deleting elements , Length of array -1.

2) If the array is empty , that shift() Method will do nothing , return undefined value .

3. Array.push(param1[,param2,...paramN])------ Add elements to the end

effect : Add an element to the end of the array , And return the length of the new array .

Be careful :1) It directly modifies the array , Instead of recreating an array .

2) It and pop Is a pair of opposite FIFO stack function methods .

3) It can add multiple elements to an array at the same time .

4. Array.unshift(newElement1[,newElement2,...newElementN])------ Add elements to the head

effect : Add one or more elements to the head of the array , And return the length of the new array .

Be careful :1) It directly modifies the array , Instead of recreating an array .

2)IE The browser does not support this method .

5.Array.join([separator])------ Convert to string

effect : Put all the elements of the array into a string .

Be careful :1) Parameters separator The separator that represents the element in a string , Can be null , The default is half width comma .

2) This method does not modify the array .

6. Array.contact(array1[,array2,...arrayN])------ Linked array

effect : Join two or more arrays into an array , And return the linked array .

Be careful :1) This method does not change the existing array , Instead, it returns a copy of the linked array .

2) If there are elements with the same value in multiple arrays , That doesn't happen again , Instead of filtering out duplicate elements .

7.Array.reverse()------ Inversion array

effect : Reverse the order of all the elements of an array .

Be careful :1) This method directly modifies the array , Instead of creating a new array .

8. Array.slice(start[, end])------ Intercept array

effect : Intercepts the elements at the specified position in the array , And returns a new subarray .

Be careful :1) This method does not change the existing array , It's a subarray of the original array .

2) Parameters start It's a must , Start subscript , If start It's a negative number , Start at the end ,-1 Represents the last element , By analogy .

3)end Is optional to indicate the end of the subscript , If not specified , To the end of the element .

9.Array.splice()------ Deletes the specified element

effect : Delete the specified number of elements from the specified position of the array , And return the deleted element .

Be careful :1) This method directly modifies the array .

2)splice() Methods and slice() The function of methods is different ,splice() Method will directly modify the array , and slice It just intercepts a part of the original array and returns a subarray , It doesn't change the original array .

10. Array.toString()------ Convert to string

effect : Array to string , And return the string .

Be careful :1) This method has no parameters join() The effect of the method is the same .

 

13.js Array weight removal , It can be realized in several ways ?

answer :

1. Use es6 set Method [...new Set(arr)]

let arr = [1,2,3,4,3,2,3,4,6,7,6];

let unique = (arr)=> [...new Set(arr)];

unique(arr);//[1, 2, 3, 4, 6, 7]

2. With the new array indexOf lookup

indexOf() Method returns the first position of a specified element in an array . If not, go back -1.

3.for Double cycle

By judging the second cycle , Whether the de duplicated array contains the element , If so, exit the second level loop , without j==result.length Equal , Then add the corresponding elements to the final array .

let arr = [1,2,3,4,3,2,3,4,6,7,6];

let result = [];

for(var i = 0 ; i < arr.length; i++) {

for(var j = 0 ; j < result.length ; j++) {

if( arr[i] === result[j]){

break;

};

};

if(j == result.length){

result.push(arr[i]);

};

};

console.log(result);

4. utilize for nesting for, then splice duplicate removal

functionunique(arr){

for(vari=0; i<arr.length; i++){

for(varj=i+1; j<arr.length; j++){

if(arr[i]==arr[j]){ // The first is equal to the second ,splice Method to delete the second

arr.splice(j,1);

j--;

}

}

}

returnarr;

}

5. utilize filter

let arr = [1,2,3,4,3,2,3,4,6,7,6];

let unique = (arr) => {

return arr.filter((item,index) => {

return arr.indexOf(item) === index;

})

};

unique(arr);

5.let arr = [1,2,3,4,3,2,3,4,6,7,6];

let unique = (arr) => {

return arr.filter((item,index) => {

return arr.indexOf(item) === index;

})

};

unique(arr);

6. utilize Map Data structure de duplication

let arr = [1,2,3,4,3,2,3,4,6,7,6];

let unique = (arr)=> {

let seen = new Map();

return arr.filter((item) => {

return !seen.has(item) && seen.set(item,1);

});

};

unique(arr);

14. Array forEach and map The difference between ?

answer :

The same thing

They loop through every item in the array

forEach and map Method supports every anonymous function execution 3 Parameters , The parameters are item( At present, every item ),index( Index value ),arr( Original array )

In anonymous functions this Is directed window

Only arrays can be traversed

Will not change the original array

difference

map Method

1.map Method returns a new array , The elements in the array are the values processed by the original array call function .

2.map Method does not detect an empty array ,map Method does not change the original array .

3. Browser support :chrome、Safari1.5+、opera All support ,IE9+,

if arr Empty array , be map Method returns an empty array .

forEach Method

1.forEach Method is used to call each element of the array , Pass the element to the callback function

2.forEach The callback function will not be called for an empty array .

No matter what arr Is it an empty array ,forEach All of them undefined. This method just takes each item in the array as callback Is executed once .

 

15.jQueryajax 、fetch、 axios What are the similarities and differences , What are the applicable scenarios ?

answer :

1.jQuery ajax

$.ajax({

type: 'POST',

url: url,

data: data,

dataType: dataType,

success: function () {},

error: function () {}

});

Advantages and disadvantages :

It's about MVC Programming for , Not in line with the current front end MVVM The wave of

JQuery The whole project is too big , Just use ajax But to introduce the whole JQuery Very unreasonable ( You can't enjoy the personalized package CDN service )

2.axios

axios({

method: 'post',

url: '/user/12345',

data: {

firstName: 'Fred',

lastName: 'Flintstone'

}

})

.then(function (response) {

console.log(response);

})

Client support prevents CSRF/XSRF

Automatic conversion JSON data

Cancel the request

Transform the request and response data

Intercept requests and responses

Support Promise API

from node.js issue http request

Created from the browser XMLHttpRequest

axios It's based on Promise For browsers and nodejs Of HTTP client , It has the following characteristics :

Why use axios?

4)fetch There is no way to monitor the progress of the request natively , and XHR Sure

3)fetch I won't support it abort, Timeout control is not supported , Use setTimeout And Promise.reject The implementation of timeout control does not prevent the request process from continuing to run in the background , It's a waste of quantity

2)fetch Default will not bring cookie, Configuration items need to be added

1)fetchtch Error only for network requests , Yes 400,500 All as successful requests , Need to be packaged to handle

Divorced from XHR, yes ES A new way of implementation in the specification

It's much lower , Provided API Enrich (request, response)

A better and more convenient way to write

In line with the separation of concerns , No input 、 Output and state tracked with events are mixed in one object

Advantages and disadvantages :

}

console.log("Oops, error", e);

} catch(e) {

console.log(data);

let data = response.json();

let response = await fetch(url);

try {

3.fetch

Provides some interfaces for concurrent requests ( important , It is convenient for many operations )

Client support prevents CSRF

Support Promise API

from node.js establish http request

Advantages and disadvantages :

});

console.log(error);

.catch(function (error) {

})

16.es6 What problems can extension operators solve ?

answer :

.. Represents an extension operator or Rest( The remaining ) Operator

 

17. Yeah, yeah js The event loop event loop?

answer :

The main thread is from " Task queue " Read events in , The process is cyclical , So the whole operation mechanism is also called Event Loop( The event loop ).

Here, I would like to recommend Mr. Ruan Yifeng's explanation event loop 's blog post :http://www.ruanyifeng.com/blog/2014/10/event-loop.html

It's quite detailed , It's easy to understand .

18.Math.min() and Math.max() Size comparison ?

answer :

Math.max() < Math.min()

Math.min() If there are no parameters , Then return to Infinity.Infinity yes javascript An attribute of the global object in , In a browser environment, it's window An attribute of an object , Infinity .

and Math.max() When no parameters are passed, the return is -Infinity.

therefore Math.min() than Math.max() Big .

 

19. How to copy objects in depth ?

answer :

Shallow copy is easy , Just use the assignment operator (=) that will do

 

20. How to continue file upload by breakpoint ?

answer :

File breakpoint resume is HTML5 New features introduced ,HTML5 Of FILE api, There is one slice Method , Can be BLOB Object segmentation . Front end by FileList Object to get the corresponding file , To segment a large file according to the specified method , And pass it on to the back end, paragraph by paragraph , At the back end, the file will be spliced in sequence .

Breakpoint continuation principle

At present, there are two methods of breakpoint continuous transmission , One is through websocket Interface for file upload , The other is through ajax, The two methods have their own merits , although websocket It sounds more high-end , But in addition to using different protocols, other algorithms are basically very similar , And the server should be enabled ws Interface , It's relatively convenient to use here ajax Let's talk about the idea of uploading at break point .

He said it , The core content of breakpoint continuation is to transfer files “ section ” And then one by one to the server .

The first is the identification of documents , How to tell the server how many pieces you cut after a file is divided into several parts , And finally how the server should merge the files you upload ?

So before the file starts to upload , We need to have one with the server “ handshake ” The process of , Tell server file information , And then agree the slice size with the server , After reaching an agreement with the server, the subsequent file transfer can be started .

The front desk should pass each piece of documents to the background , After success, both the front end and the back end should be identified , So that subsequent breakpoints .

When the file transmission is interrupted, the user can select the file again to determine whether a part of the file has been uploaded through the identification , If so , Then we can continue to transfer documents according to the last progress , To achieve the function of continuous transmission .

21.js How to deal with anti shake and throttle ?

answer :

In the window resize、scroll, Input box content verification and other operations , If the frequency of event handler calls is unlimited , Will increase the burden of the browser , Leading to a very bad user experience .

At this point, we can use debounce( Shake proof ) and throttle( throttle ) To reduce the frequency of calls , At the same time, it does not affect the actual effect .

Function anti shake

Function anti shake (debounce): When the event is triggered continuously , No more triggers for a certain period of time , The event handler will only execute once , If the set time comes before , It triggered the event again , Start the delay again .

as follows , Continue to trigger scroll When an event is , Not implemented handle function , When 1000 No trigger in milliseconds scroll When an event is , Will delay the trigger scroll event .

function debounce(fn, wait) {

var timeout = null;

return function() {

if(timeout !== null) clearTimeout(timeout);

timeout = setTimeout(fn, wait);

}

}

// Processing function

function handle() {

console.log(Math.random());

}

// Scroll Events

window.addEventListener('scroll', debounce(handle, 1000));

Function throttling

Function throttling (throttle): When the event is triggered continuously , Make sure to call the event handler only once in a certain period of time .

The common explanation for throttling is that we drain water from faucets , As soon as the valve opens , The water splashed down , Adhere to the fine traditional virtues of thrift , We need to turn down the tap , It's better if we are willing to follow a certain rule and drop by drop in a certain time interval .

as follows , Continue to trigger scroll When an event is , Not immediately handle function , every other 1000 Only once in milliseconds handle function .

var throttle = function(func, delay) {

var prev = Date.now();

return function() {

var context = this;

var args = arguments;

var now = Date.now();

if (now - prev >= delay) {

func.apply(context, args);

prev = Date.now();

}

}

}

function handle() {

console.log(Math.random());

}

window.addEventListener('scroll', throttle(handle, 1000));

summary

Function anti shake : Combine several operations into one operation for . The principle is to maintain a timer , It is stipulated in delay Trigger function after time , But in delay If it's triggered again in time , Will cancel the previous timer and reset . thus , Only the last operation can be triggered .

Function throttling : To trigger a function only once in a certain period of time . The principle is to trigger the function by judging whether it has reached a certain time .

difference : Function throttling doesn't matter how often events are triggered , Will ensure that a real event handler will be executed within the specified time , Function anti shake only triggers a function after the last event . For example, in the infinite loading scenario of the page , We need users to scroll the page , Every once in a while Ajax request , Instead of requesting data when the user stops scrolling the page . Such a scene , It is suitable to use throttling technology to achieve .

 

22. Event delegation and its advantages and disadvantages

answer :

advantage :

1. Reduce event registration , Save memory . such as ,

2. stay table On behalf of all td Of click event .

3. stay ul On behalf of all li Of click event .

4. To simplify the dom When the node is updated , Update of corresponding events . such as

5. No need to add new li The binding click event .

6. When deleting something li when , You don't have to remove it click event .

shortcoming :

1. Event delegation is based on bubbling , For events that don't bubble .

2. Too many levels , In the process of bubbling , It may be blocked by some layer .

3. In theory, delegation causes browsers to call processing functions frequently , Although it's probably not necessary to deal with . Therefore, it is suggested to entrust it nearby , For example table Agency td, Not in document Agency td.

4. Using agents for all events may result in event miscalculation . such as , stay document In the agency of all button Of click event , Others are quoting js when , May not know , Causes a click button Triggered two click event .

23. Introduce this All kinds of situations

answer :

- this The situation of :

1. When called as a function ,this It's always window

2. When called as a method ,this It's the object that calls the method

3. When called as a constructor ,this It's the newly created object

4. Use call and apply Invocation time ,this It's the designated object

5. Arrow function : Arrowhead function this See if there's a function in the outer layer

If there is , Of outer functions this It's the function of the inner arrow this

without , Namely window

6. A special case : Generally speaking this The pointer points to the object that is calling it last . One thing to note here is that if the return value is an object , that this Point to the returned object , If the return value is not an object this Or an instance of a function

24.== and === The difference between , When to use equality ==

answer :

==: The operator is called equality , Used to detect whether two operands are equal , The definition of equality here is very loose , Type conversion can be allowed

===: Used to detect whether two operands are strictly equal

1、 about string,number Equal foundation type ,== and === There is a difference

Comparison between different types ,== Comparison “ Values converted to the same type ” see “ value ” Whether it is equal or not ,=== If the type is different , The result is unequal

Comparison of the same type , Go straight ahead “ value ” Compare , The results are the same

2、 about Array,Object And so on ,== and === There is no difference

3、 Basic type and advanced type ,== and === There is a difference

about ==, Convert advanced to base type , Conduct “ value ” Compare , Because of the different types ,=== The result is false

25. Introduce the prototype chain ( Is the problem of inheritance solved )

answer :

JavaScript Prototype :

Each object initializes a property inside it , Namely prototype( Prototype ).

Prototype chain :

When we access the properties of an object , If this property does not exist inside this object , Then he will go prototype Find this property in , This prototype I'll have my own prototype, So I kept looking for it , That's what we usually call the concept of prototype chain .

characteristic :

JavaScript Objects are passed by reference , None of the new object entities we create has its own prototype copy . When we modify the prototype , The objects associated with it will also inherit this change .

26.JS What is the garbage collection mechanism in , What kind is commonly used , How to deal with ?

answer :

JS Garbage collection mechanism is to prevent memory leakage , The meaning of memory leak is that when a certain block of memory is no longer needed, it still exists , Garbage collection mechanism is to find variables that are no longer used intermittently and irregularly , And free up the memory they point to .

JS The most common garbage collection method in is mark removal .

working principle : When a variable enters the environment , Mark this variable as “ Enter the environment ”. When a variable leaves the environment , Mark it as “ Leaving the environment ”. Mark “ Leaving the environment ” Reclaim memory .

Workflow :

1. Garbage collector , All variables stored in memory are marked at run time .

2. Remove tags for variables in the environment and variables referenced by variables in the environment .

3. The marked variable will be regarded as the variable to be deleted .

4. Garbage collector completes memory cleaning , Destroy the tagged values and reclaim the memory space they occupy .

27.Promise and setTimeout The difference between ?

answer :

review JavaScript Event loop concurrency model , We get it setTimeout and Promise All the calls are asynchronous tasks , This is what they have in common , In other words, they are all managed through task queues / Dispatch . So what's the difference between them ?

Task queue

The basic content and mechanism of task queue have been introduced earlier , You can choose to view , This paper introduces the task queue expansion .JavaScript Manage all asynchronous tasks through a task queue , The task queue can also be subdivided into MacroTask Queue and MicoTask Queue Two types of .

MacroTask Queue

MacroTask Queue( Macro task queue ) It mainly includes setTimeout,setInterval, setImmediate, requestAnimationFrame, NodeJS Medium `I/O etc. .

MicroTask Queue

MicroTask Queue( Micro task queue ) There are two main categories :

Independent callback microTask: Such as Promise, Its success / The failure callback functions are independent of each other ;

Compound callback microTask: Such as Object.observe, MutationObserver and NodeJs Medium process.nextTick , Different state callbacks in the same function body ;

MacroTask and MicroTask

JavaScript Divide asynchronous tasks into MacroTask and MicroTask, So what's the difference between them ?

Execute the synchronization code in sequence until the execution is complete ;

Check MacroTask queue , If there is a triggered asynchronous task , Take the first one and call its event handler , Then jump to step three , If there is no asynchronous task to process , Go straight to step three ;

Check MicroTask queue , Then execute all triggered asynchronous tasks , Execute the event handler in turn , Until it's done , Then jump to step two , If there is no asynchronous task to handle , Go back to step 2 , Follow the next steps in turn ;

Finally, back to the second step , To continue to check MacroTask queue , Follow the next steps in turn ;

So back and forth , If all asynchronous tasks are processed , End ;

28. Introduce next breadth first traversal (BFS) And depth first traversal (DFS)?

answer :

 

1. Breadth first traversal

The abbreviation is BFS namely Breadth FirstSearch. The process inspection is to access the nodes of each layer in turn , Go to the next level after visiting one level , And each node can only access once . For the example above , Breadth first traversal The result is :A,B,C,D,E,F,G,H,I( Suppose that each layer of nodes accesses from left to right ).

First insert the left node into the queue , Then insert the right node , In this way, the left node is the first and then the right node .

Breadth first traversal tree , You need to use queues (Queue) To store node objects , The characteristics of queues are first in, first out . for example , The visit to the above tree is as follows :

First of all, will A The node is inserted into the queue , There are elements in the queue (A);

take A Node pop up , At the same time A The left side of the node 、 The right node inserts the queue in turn ,B At the head of the team ,C At the end of the team ,(B,C), Now get A node ;

Continue to pop the team leader element , Pop up B, And will B Left of 、 The right node is inserted into the queue ,C At the head of the team ,E At the end of the team (C,D,E), Now get B node ;

Continue to pop up , Pop up C, And will C The left side of the node 、 in 、 The right node inserts the queue in turn ,(D,E,F,G,H), Now get C node ;

take D eject , here D No child node , The elements in the queue are (E,F,G,H), obtain D node ;

... And so on ..

2. Depth-first traversal

The abbreviation is DFS namely Depth First Search. The process is simply to drill down every possible branch path to the point where it can't go further , And each node can only access once . For the above example, the result of depth first traversal is :A,B,D,E,I,C,F,G,H.( Suppose you go to the left side of the child node first ).

Depth first traverses each node , Need to use to stack (Stack) This data structure .stack It is characterized by being first in and then out . The whole traversal process is as follows :

First push the right node into the stack , Press the left node again , In this way, the left node is first followed by the right node .

First of all, will A Nodes are pushed onto the stack ,stack(A);

take A Node pop up , At the same time A Child nodes of C,B Pressure into the stack , here B At the top of the stack ,stack(B,C);

take B Node pop up , At the same time B Child nodes of E,D Pressure into the stack , here D At the top of the stack ,stack(D,E,C);

take D Node pop up , No child nodes are pressed in , here E At the top of the stack ,stack(E,C);

take E Node pop up , At the same time E Child nodes of I Push the ,stack(I,C);

… Down in turn , Finally, the traversal is completed .

Code : Take a binary tree as an example .

 

29.for in and for of The difference between

answer :

1. It is recommended to loop object properties , Use for...in, Used when traversing arrays for...of

2.for...in What circulates is key,for...of What circulates is value

3. Be careful ,for...of yes ES6 New features . Repair the ES5 Introduced for...in Deficiency

4.for...of You can't cycle through ordinary objects , Need to pass and Object.keys() Use it with

30.typeof and instanceof difference ?

answer :

stay javascript in , To determine the type of a variable, you can use typeof

(1) Numeric type 、typeof The value returned is number. for instance :typeof(1), The return value is number

(2) String type ,typeof The value returned is string. such as typeof(“123” On return value string)

(3) Boolean type ,typeof The value returned is boolean. such as typeof(true) On return value boolean

(4) object 、 Array 、null The value returned is object. such as typeof(window),typeof(document),typeof(null) The returned values are object

(5) Function type , The value returned is function. such as :typeof(eval),typeof(Date) The returned values are function.

(6) Variables that don't exist 、 Function or undefined, Will return undefined. such as :typeof(abc)、typeof(undefined) All back to undefined

stay javascript in ,instanceof Used to determine whether an object is constructed by another function .

Use typeof There is a problem with using reference types to store values when using operators , No matter what type of object is referenced , It is returned ”object”.ECMAScript Another one was introduced Java Operator instanceof To solve this problem .Instanceof Operators and typeof Operators are similar , Used to identify the type of object being processed . And typeof The difference is ,instanceof Method requires the developer to explicitly confirm that the object is of a certain type

31. There are several common ways of inheritance

answer :

1. Prototype chain inheritance

2. Constructor inheritance ( Classic inheritance )

3. Combination inheritance ( Constructors + Prototype chain )

4.es6 Method inheritance

 

 

版权声明
本文为[Li gulare]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple