Home > Web Front-end > JS Tutorial > body text

Take a look at these front-end interview questions to help you master high-frequency knowledge points (7)

青灯夜游
Release: 2023-02-27 18:59:10
forward
1501 people have browsed it

Take a look at these front-end interview questions to help you master high-frequency knowledge points (7)

10 questions every day, after 100 days, you will have mastered all the high-frequency knowledge points of front-end interviews, come on! ! ! , while reading the article, I hope you don’t look at the answer directly, but first think about whether you know it, and if so, what is your answer? Think about it and then compare it with the answer. Would it be better? Of course, if you have a better answer than mine, please leave a message in the comment area and discuss the beauty of technology together.

Interviewer: Please talk about the this pointing issue in JS

Me: Uh~, we know this in thisThere is a rule that whoever calls points to whom. This sentence will subtly lead to some misunderstandings. The possible errors are summarized as follows, and the code is provided:

1) We need to know that if we get this globally, this will point to windows, because everything we use globally will be mounted on the window.

<script>
    console.log(this) // 指向window
    function a(){
        console.log(this)
    }
    a() // 相当于 window.a(),指向的依旧是 window
</script>
Copy after login

2) I need to know that the point of this will point to the previous caller. The code is as follows:

After reading the code, we know that although the d function is essentially called because of a , but there is still a layer in the middle where c calls the d function, so this points to the upper level and there is a proximity principle. This is very important! ! !

<script>
    var a = {
        b:10,
        c:{
            b:12,
            d:function(){
                console.log(this)
            }
        }
    }
    a.c.d() // {b: 12, d: ƒ}
</script>
Copy after login

3) We need to know that the arrow function has no scope, that is to say, it does not have its own this. Its this always points to the upper-level this. Here is a example from a major manufacturer Interview question, can you guess what the final printed result is?

Assuming you have read this interview question carefully, I believe you already know the answer is 66. Why? , you must know that the arrow function does not have its own this, so it needs to go to the upper level to find this, and the upper level is in the global scope, so what is printed is the globally mounted ID number 66.

<script>
    var id = 66
    function a(){
        setTimeout(()=>{
            console.log(this.id)
        },500)
    }
    a({id:22}) // 猜猜结果是什么?
</script>
Copy after login

Then how do we change the point of this to control this to point to the result we want? The following three methods are given:

<script>
    var id = 66
    function a(){
        setTimeout(()=>{
            console.log(this.id || this)
        },500)
    }
    // call => {} 改变之后并执行一次
    a.call({id:22}) // 打印22 

    // apply => [] 改变之后并执行一次
    a.apply([12]) // 打印 [12]

    // bind() 不调用,只改变this指向
    a.bind(a(id=32)) // 32
</script>
Copy after login

Interviewer: Tell me about the functions and differences of call apply bind?

Me: Uh~, okay, the summary is as follows:

The three methods of call apply bind can be used to change the this point of the function , the specific differences are as follows:

1) fn.call (newThis,params) The first parameter of the call function is the new pointer of this, and then the functions to be used by fn are passed in sequentially. parameter. The fn function will be executed immediately.

2) fn.apply (newThis,paramsArr) The first parameter of the apply function is the new pointer of this, and the second parameter is the parameter array to be used by fn, and the fn function will be executed immediately.

3) fn.bind (newThis,params) The first parameter of the bind function is the new pointer of this. The subsequent parameters can be passed directly or in the form of an array. The fn function will not be executed immediately, and the pointing of the fn function can only be changed once. Subsequent changes using bind will be invalid. What is returned is the new fn that has changed the point of this

Interviewer: Please talk about your understanding of event delegation

Me: Uh~ Well, event delegation uses event bubbling to manage all events of a certain type by specifying only one event handler. To put it bluntly, it means attaching events that have not yet occurred to events that have already occurred. The entire code is as follows:

<body>
<ul id="ul">
    <li>0</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
<button id="btn">点我添加一个li</button>
<script>
    // 事件委托
    let ul = document.getElementById("ul")
    ul.addEventListener('click',(event)=>{
        console.log(event)
        event = event || window.event
        let target = event.target
        if(target.nodeName == 'LI'){
            alert(target.innerHTML)
        }
    })

    let btn = document.getElementById('btn')
    btn.addEventListener('click',()=>{
        let li = document.createElement('li')
        li.textContent = ul.children.length
        ul.appendChild(li)
    })
</script>
</body>
Copy after login

Interviewer: Tell me what promise is and how to use it?

Me: Uh~, okay, Promise is a constructor provided by ES6. You can use the Promise constructor new to create an instance. The Promise constructor receives a function as a parameter. This function has Two parameters, namely the two functions resolve and reject, resolve Change the state of Promise from waiting to success, and pass the result of the asynchronous operation as a parameter; reject changes the state from waiting to failure, and call it when the asynchronous operation fails. Errors reported by asynchronous operations are passed as parameters. After the instance is created, you can use the then method to specify success or failure callback functions respectively, or you can use catch to capture failure,then and catch ultimately return a Promise, so they can be called in a chain.

The role of Promise:

Promise is an asynchronous micro-task, which solves the problem of asynchronous multi-layer nested callbacks and makes the code readable Higher performance and easier to maintain Promise using

Characteristics of Promise:

1) The state of the object is not affected by the outside world

2) Once the state changes, it will not change again. You can get this result at any time

3) The parameters of the resolve method are the parameters of the callback function in then, and the parameters of the reject method are the parameters of catch. Parameters

4) As long as the then method and catch method do not report an error, they will return a fullyfilled promise

Application scenario:

Solve the hell callback problem

For specific usage methods, please refer to my previous article: Understand Promise in JS in one article

Interview Official: Tell me what cross-domain is? How to solve cross-domain issues?

Me: Uh, okay, the summary is as follows:

What is cross-domain:

If the address requested by an interface in the current page is different from the address of the current page, the interface is said to be cross-domain.
Reasons for cross-domain restrictions:

In order to ensure the security of web pages, the browser has a same-origin protocol policy.

Cross domain solution

cors

Currently One of the most common solutions is to allow cross-domain implementation by setting up a backend.
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader("Access-Control-Allow-Methods", "GET, PUT, OPTIONS, POST");

node middleware, nginx reverse proxy

The browser cannot access the server across domains when there are cross-domain restrictions, node middleware and nginx reverse proxy allows requests to be sent to the proxy server. The static page and the proxy server have the same origin, and then the proxy server sends requests to the back-end server. There is no homology restriction between the server and the server.
JSONP

The principle used is that the script tag can request resources across domains, and the callback function is spliced ​​into the url as a parameter. The backend receives the request, calls the callback function, and returns the data as a parameter. Pay attention to setting the response header to return the document type, which should be set to javascript.

Interviewer: How many methods does JavaScript have to determine the type of a variable?

Me: Uh, okay, JavaScript has 4 ways to determine the type of a variable, summarized as follows:

typeof:

Often used to determine basic data types. For reference data types, except function, return 'function', and the rest return 'object'.

instanceof:

is mainly used to distinguish reference data types. The detection method is to detect the type on the prototype chain of the current instance and use it The detected results are all true

Object.prototype.toString.call()(Object prototype chain judgment method):

Applicable to all types of judgment detection, the detection method is Object .prototype.toString.call(data) returns a string of this data type.

constructor(for reference data type):

is used to detect the reference data type. The detection method is to obtain the instance's constructor judgment and Whether a certain class is the same, if it is the same, it means that the data conforms to that data type. This method will not add other classes on the prototype chain, avoiding interference from the prototype chain.

Interviewer: Tell me about the method of asynchronous implementation in JS?

Me: Uh~, okay, all asynchronous tasks are taken out from the task queue and executed sequentially after the execution of the synchronous task is completed. Common ways to implement asynchronous implementation are as follows:

Callback function, event listening, setTimeout (timer), Promise, async/await, generator generator

Interviewer: Tell me what are the methods for deduplicating arrays?

Me: Uh~, there are many ways to remove duplicates from arrays. Here are a few examples and simple explanations, as follows:

Use Object attribute key excludes duplicates:

Traverse the array and determine whether the attribute exists in the object each time. If it does not exist, store it in a new array, and use the array element as the key to set a The value is stored in the object and finally the new array is returned.

Use Set type data to have no duplicates

new a Set whose parameters are arrays that need to be deduplicated. Set will automatically delete duplicates elements, and then convert the Set into an array and return it.

filter indexof deduplication:

Use the filter method that comes with Array to return arr.indexOf(num) equal to the num of index.

reduce includes deduplication

Use reduce to traverse and pass in an empty array as the new array after deduplication, and then internally determine the new Whether the currently traversed element exists in the array, if not, it is inserted into the new array.

Interviewer: Tell us about the arrow function in es6?

Me: Uh~, okay, the arrow function is equivalent to an anonymous function, which simplifies the function definition. There are two ways to write arrow functions. When the function body is a single statement, {} and return can be omitted. The other is to contain multiple statements, and {} and return cannot be omitted. The biggest feature of the arrow function is that it does not have this, so this is obtained from the outside, that is, it inherits this in the external execution context. Since there is no this keyword, the arrow function cannot be used as a constructor.

Arrow functions are more concise, clear and fast than the definition of ordinary functions. But there is a difference between the two: the arrow function does not have prototype prototype and super, so it cannot create this. Its this is obtained by inheriting the variables in the external function environment, so call, bind, and apply cannot change the point of its this; looking for When reaching the outermost ordinary function, its this generally points to window; arrow functions cannot use new; arrow functions have no arguments; they cannot be used as generator functions and cannot use the yield command; arrow functions cannot be used for dynamic this in object fields and callback functions. , generally used internally without this reference.

Interviewer: Let’s talk about JS variable promotion?

Me: Uh~, okay, variable promotion means that JS variable and function declarations will ,## during the code compilation period #Promote to the front of the code. The premise for variable promotion is that the variable is declared using the Var keyword, and when the variable is promoted, only the declaration is promoted, and the assignment is not promoted. At the same time, the declaration promotion of the function will take precedence over the promotion of the variable. As a result of variable promotion, the variable can be accessed before the variable is initialized, and undefined is returned. The function can be called before the function is declared.

Variables declared using let and const are created and promoted, forming a temporary dead zone. Accessing variables created by let and const before initialization will result in an error.

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of Take a look at these front-end interview questions to help you master high-frequency knowledge points (7). For more information, please follow other related articles on the PHP Chinese website!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template