interview-question-note(1)

Stabilization and throttling

Stabilization and throttling are practical applications of closures

Anti-shake function

The event processing function will be executed once when the event is continuously triggered and the event is not triggered again within a certain period of time. If the event is triggered again before the set time arrives, the delay will start again
. no retype

A memory leak refers to variables that you can't use (can't access), still occupy the memory space, and can't be used again.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖函数</title>
</head>
<body>
    <input type="text" id="input">

    <script>
        // document.querySelector('#input').addEventListener('keyup',function(e){ debounce(1000,e.target.value)})
        // let timer = null
        // function debounce(delay,value){
      
      
        //     clearTimeout(timer)
        //     timer =setTimeout(function(){
      
      
        //         console.log(value);
        //     },delay)
        // }
        // 一直在内存当中 内存泄漏 闭包
        // 内存泄露是指你用不到(访问不到)的变量,依然占居着内存空间,不能被再次利用起来。  
        // 函数柯里化
        //以上完成了基本需求但是我们定义了一个全局变量,基于尽可能少的使用全局变量
        // 我们将变量放入debounce函数的内部
        document.querySelector('#input').addEventListener('keyup',function(e){
      
       debounceFuc(e.target.value)})
        var debounceFuc = debounce(1000,fn)
        // 前面为什么要用callback是因为可以封装 不然写死了 用一个防抖就得重复写 callback灵活
        function debounce(delay,callback){
      
      
            let timer = null
            return function(value){
      
      
              clearTimeout(timer)
              timer = setTimeout(function(){
      
      
            //    console.log(value);
            callback(value)
              },delay)
            }
        } 
        function fn(value){
      
      
            console.log(value);
        }

        // 这里是基于闭包实现的,按钮 element 监听了 click 事件,并执行 debounce 方法,debounce 方法又返回一个新函数
        // ,这里的 timer 就会一直存在,不被销毁,因为函数被外部引用。
        // 所以下次点击的时候 timer 还是存在,我们点击的时候首先会 clearTimeout,也就是取消上次的请求
    </script>
</body>
</html>

Practical application scenarios

When using echarts, when changing the width of the browser, you want to re-render
the image of echarts. You can use this function to improve performance (although echarts has its own resize function).
Typical case: the search request is made n seconds after the end of the search input , if the content is input again within n seconds, the timing will be restarted
to solve the search bug

Throttle function

When the event is continuously triggered, it is guaranteed that the event processing function is called only once in a period of time, and
only one thing is done in a period of time

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>节流函数</title>
</head>
<body>
    <button id="button">点击</button>
    <script>
        document.querySelector('#button').onclick = throttle(handle,2000)
        let timeOut = null
        function throttle(func,wait){
      
      
         
         return function(){
      
      
            if(!timeOut){
      
      
                timeOut = setTimeout(function(){
      
      
                 func()

                 timeOut = null
                },wait)

            }
         }
        }
        function handle(){
      
      
            console.log(Math.random());
        }
    </script>
</body>
</html>

Practical application scenarios

Typical case: the mouse clicks continuously to trigger, and it is stipulated that only one click will take effect within n seconds

Anti-shake throttling optimize image lazy loading

Anti-shake - optimize the window changes that are triggered continuously
Recalculate the height of the visible area
Throttling - implement lazy loading with better performance
Display of pictures when sliding

Login authentication

Traditional login authentication scheme

insert image description here
insert image description here
insert image description here
Distributed, same-domain single sign-on session synchronization solution
1.IPhash

The most primitive way is the iphash method. The hash value is calculated by the IP value. For the first time, the client's request is sent to system A by the proxy server nginx, and then every time it is the hash value of the IP, it is sent to system A. Although this can solve the problem, it is false load balancing. If system A hangs up, it will cause the system to be paralyzed, and the user cannot use it normally, which will cause a single point of failure. This method has long since been eliminated.

2.session replication

The code logic of cluster servers is the same. After a user logs in to system A, his login information is saved in the session domain. Cluster servers can communicate and perform session synchronization. The point of explanation is to copy your own session to other servers to ensure that the data in the session domain of all normal working clusters is exactly the same, so that everyone knows that this user has logged in.
3. Intermediate storage medium

The third method is improved on the basis of the second method. Instead of saving a copy of data for each cluster, after each server finishes processing, save the data to a third-party storage structure. All servers will fetch data from third-party storage structures. Generally, non-relational database Redis is used as third-party storage.
As shown in the figure, whether it is a distributed server or a cluster server, after the user logs in, an id that can uniquely identify the client will be generated, and the id will be used as the key, and the client's login information will be stored in Redis with the user as the value, and then will Return the key value to the client in the form of Token. When the client initiates a request here and sends it with the Token, no matter which server processes the request, it will get the uuid from the Token, and then go to Redis to find the user's information. This enables single sign-on.

4. Summary
Session synchronization technology enables both cluster servers and distributed servers to share user login information. It has contributed a lot to the realization of single sign-on.

The token-based authentication scheme is the third intermediate storage media solution
insert image description here

jwt authentication scheme

The jwt scheme is the most used now
insert image description here
insert image description here

Precompiled

The stage of scope creation is the stage of precompilation.
Those things are done during precompilation. The
js variable object AO object is accessed by the js engine itself.
The four steps of precompilation
are 1. Create ao object
2. Find formal parameters and variable declarations as The attribute name value of the ao object is undefined
3 The actual parameter and the formal parameter are unified
4 Find the function declaration (the function declaration will override the variable declaration)

insert image description here

this

In the function,
the function is directly used as the method of the object to be called (I will point to whoever calls me)

insert image description here
The above writing method is the grammatical sugar of the call writing method

insert image description here

arrow function

insert image description here

Handwritten implementation of call apply

The difference between the functions of call apply Understand the actual development scenario
Change this to point to the parameter difference Call one-way data apply array
js inherit prototype chain inherit constructor inherit call to realize
js data type
es5 pseudo array into array

Scenarios of using call in actual combat

  • Implement js inheritance
  • Judging complex data types
  • es5 pseudo-array converted to array
console.log(Object.prototype.toString.call({
    
    })==='[object Object]');
console.log(Object.prototype.toString.call([])==='[object Array]');
 function get() {
    
    
            console.log(arguments);
            console.log([...arguments]);    //es6
            console.log(Array.prototype.slice.call(arguments));  //es5
        }
        get(1, 2, 3)

The function of call changes the point of this

        var person = {
    
    
            getName:function(){
    
    
                return this.name
            }
        }
        var person1 = {
    
    
            name:'zhangyue'
        }
        console.log(person.getName.call(person1));

Realize handwritten call

tips: JS—arguments object
arguments is an array-like object (pseudo-array). Represents a list of parameters passed to a function.

         var person = {
    
    
            getName:function(){
    
    
                return this.name
            }
        }
          var person1 = {
    
    
            name:'zhangyue'
        }
        // 参数接收的 改变this指向的参数
        Function.prototype.myCall = function(context){
    
    
            // 这里面的this是谁   是getname 因为谁调用this就指向谁
            // 这里的this必须是一个function
            if(typeof this !== 'function'){
    
    
                throw new Error('error')
            }
            // context = context || window  传了就是context 不传就是window
            // 考虑参数    拿到除了第一个参数之外的参数
            var args = [...arguments].slice(1)
            console.log(args);
            context.fn = this
            var result = context.fn(args)
            return result
        }
       
        console.log(person.getName.myCall(person1,1,2,3));

Event loop mechanism even-loop

js language features

  • single thread
  • interpreted language

The event-loop event loop mechanism consists of three parts

  • call stack
  • microtask queue
  • message queue

At the beginning of the even-loop, it will be executed line by line from the global level. When a function call is encountered, it will be pushed into the call stack. The pushed function is called a frame. When the function returns, it will be popped from the call stack.

When asynchronous operations in js such as fetch setTimeout setInterval are pushed into the call stack, the messages inside will enter the message queue, and those in the message queue will wait until the call stack is cleared before executing

The asynchronous operation of promise async await will be added to the microtask and will be executed immediately when the call stack is cleared. The
microtask added to the call stack will be executed immediately
insert image description here

BFC

Understanding of BFC

Block-level formatting context , which refers to an independent block-level rendering area, only Block-level BOX (block-level box) participates , this area has a set of rendering rules to constrain the layout of block-level boxes, and has nothing to do with the external area

Start with a phenomenon

  • A box does not set height, when the content elements are all floating, it cannot support itself,
    then this box has no bfc

How to create a BFC

  • float is not none
  • position is not static or relative
  • display 为 iinline-block,flex,inline-flex
  • overflow 为 hidden

Other functions of BFC

  • Cancel box margin collapse
  • Prevents elements from being covered by floated elements

Margin collapse
insert image description here
What you want is that the child box has a top margin from the parent box, but the parent box is brought down together.
Add overflow: hidden to the parent element; enable BFC to solve the problem of margin collapse

Prevent elements from being covered by floating elements
insert image description here
Blue floating elements cover the red box, set overflow: hidden for red; solve the problem of being covered

deep copy shallow copy

Pre-knowledge

data storage

  • General data type
    number string boolean null undefined Symbol
  • Reference data type
    object array Set Map

General data types are stored on the stack, including its name and value,
while complex types such as objects have their names on the stack, but their real content is on the heap, and the stack
only stores its references.
insert image description here

The difference between assignment and shallow copy

Assignment The assigned object and the original object reference are the same, changing the current original object will also change

shallow copy

  • A new object is created
  • Copy value (if the attribute is a general data type, the value of the basic type is copied; if the attribute is a reference data type, the memory address is copied)
        var num = 123
        var person = {
    
    name:'张三'}

        var person1 = person
        person1.name = '李四'
        console.log(person.name);  //李四
        console.log(person1.name); //李四
        // 上面的代码是浅拷贝吗?
        // 不是浅拷贝 上面的操作是赋值

        // 浅拷贝
        // 创建一个新的对象
        // 层次的理解
        // 拷贝值 (如果属性是一般数据类型 拷贝的是基本数据类型 
        // 如果属性是引用数据类型 那么拷贝的就是内存的地址)
        // 说的直白一点 浅拷贝如果碰到的是引用数据类型 那么拷贝前和拷贝后是相互影响的

        // 深拷贝
        // 如果属性是引用类型,那么就会开辟一个新的空间
        var person3 = {
    
    name1:'张三',name2:'张三222',name3:'张三333',hobby:['篮球','足球']}

        function shallowClone(source){
    
    
            var newObj = {
    
    }
            for (var i in source){
    
    
                // console.log('i',i);
                if(source.hasOwnProperty(i)){
    
    
                    newObj[i] = source[i]
                }
            }
            return newObj
        }
        person4 = shallowClone(person3)
        // person5 = deepClone(person3)
        person4.name1 = '李四'
        person4.hobby[1] = '冰球'
        // person4.hobby = '冰球'
        // console.log(person5); 
        console.log(person4); 
       console.log(person3); 

        // 这里使用的hasOwnProperty的原因是:
        // for in 会遍历到原型链上的属性,所以要用这个判断,遍历到的属性是不是确实在source对象上面的
        // hasOwnProperty(属性名)确认该属性是否是其对象的自有属性,若是则返回true

insert image description here

Application Scenarios of Deep and Shallow Copy

The modification in vue addition, deletion, modification and checking uses deep and shallow copy

Cross-domain processing of front-end and back-end interactions

The proxy must figure it out.
After the proxy, there will be an extra /api in front of the address. There are two solutions:
insert image description here
1. Add /api before the back-end interface
insert image description here
2. Add rewrite to the front-end

insert image description here

utils - storage.js is the encapsulation of localstorge.
Is vuex persistent storage? Will it be lost after the page is refreshed?

Optimizing Conditional Statements Dachang Interview Questions

insert image description here

 function printAnimalsDetails({
     
     type,name,gender}={
     
     }){
    
    
           if(!type) return 'no animal type'
           if (!name) return 'no animal name'
           if(!gender) return 'no animal gender'
           return `${
      
      name} is ${
      
      gender} - ${
      
      type}`
        }
        console.log(printAnimalsDetails({
    
    name:'zhangsan'}));
        console.log(printAnimalsDetails({
    
    name:'zhangsan',type:'gg',gender:'nan'}));
        console.log(printAnimalsDetails());

Tips: How to set ctrl+wheel zoom in vscode
insert image description here

Guess you like

Origin blog.csdn.net/weixin_51867622/article/details/129179965