Front end basic knowledge sorting

  • Rearrange (reflow) reflow and repaint

    Rearrangement: when the position or size of DOM elements changes, the browser needs to recalculate the geometric attributes of the elements and put the elements in the normal position. This process is rearrangement.

    Redrawing is the process of redrawing the appearance of DOM elements when their appearance changes but their layout is not changed. It is called redrawing.

    Too many rearrangements and redraws will affect page performance

    Reduce the number of times to change the layout operation of the same element at one time. For example, if JS operates the elements top and left, it will be generated twice. (try not to put the read operation and write operation in one statement, which will cause two or more rearrangements and redraws).

    For elements with animation, use POSITION's absorb or FIXED to separate them from the document, which will not affect other elements when realizing animation.

  • prototype

    Prototype is the basis of inheritance in JavaScript. JavaScript inheritance is based on prototype implementation. Although there is a class keyword in ES2015/ES6, it is only a syntax sugar. Finally, it is inherited through prototype.

    function Student(){}
    Student.prototype.sayHi=function(){console.log('hi')}
    
    var stu = new Student()
    

    As above, a Student Object is defined, and a sayHi method is defined on the prototype of the Object. When the Student Object is instantiated, the stu entity Object will exist__ prto__ Property points to the prototype of Student, and the prototype of Student also exists__ proto__ Prototype pointing to Object

    • inherit

      class Person {
          constructor(name) {
              this.name = name
          }
      
          eat() {
              console.log(`${this.name} eat`)
              return this
          }
      }
      
      class Student extends Person {
          constructor(name, number){
              super(name)
              this.number = number
          }
      
          sayHi() {
              console.log(`${this.name}-${this.number}`)
              return this
          }
      }
      
      class Teacher extends Person{
          constructor(name, classes){
              super(name)
              this.classes = classes
          }
          sayHi() {
              console.log(`${this.name}-classess:${this.classes}`)
              return this
          }
      }
      
      
      const stu = new Student('student', 22).sayHi().eat()
      const tech = new Teacher('teacher', 'c-1').sayHi().eat()
      console.log(stu instanceof Student)
      console.log(stu instanceof Person)
      console.log(stu instanceof Object)
      
      console.log(typeof Student)
      console.log(typeof Person)
      
      console.log(Person.prototype === Student.prototype.__proto__
      
  • Variable and this search summary

    All free variables are searched not when the function is executed, but when the function is defined

    this is found when the function is executed, not when the function is defined

  • EventLoop

EventLoop is the implementation principle of asynchronous execution in JS. It mainly involves micro tasks and macro tasks.

Micro tasks include Promise, async / wait.

Macro tasks have setTimeout, setinteval, Ajax and DOM events

The main difference between micro task and macro task is the rendering time of DOM elements. Micro task executes earlier than macro task

Example:

// Micro and macro tasks
async function async1() {
    console.log('async1 start') //2
    await async2() //Micro task, followed by callback micro task
    console.log('async1 end') //6
}

async function async2(){
    console.log('async2') //3
}

console.log('script start') // 1

setTimeout(function(){
    console.log('setTimeout') //8
},0)

async1()
new Promise(function(resolve){
    console.log('promise1') //4
    resolve() // Micro task
}).then(function(){
    console.log('promise2') //7 
})

console.log('script end') //5
  • AJAX

    const xhr = new XMLHttpRequest()
    xhr.open('GET','/API', true) // FALSE synchronous, TRUE asynchronous
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4){
            if(xhr.status === 200) {
                alert(xhr.responseText)
            }else{
                alert('other')
            }
        }
    }
    xhr.send(null)
    
    • readyState

      value state describe
      0 UNSET The proxy was created, but the open() method has not been called
      1 OPENED The open() method has been called
      2 HEADERS_RECEIVED The send() method has been called, and the header and state are available
      3 LOADING Downloading; The responseText property already contains some data
      4 DONE Download operation completed
    • status

      http request return code, 1xx client has sent the request, 2xx completion, 3xx redirection, caching, etc. (302 redirection, 304 caching), 4xx client error, 5xx server error (504 gateway request timeout)

  • Anti shake and throttling

    Anti shake means that the function will be executed only once within N seconds after the frequency modulation event is triggered. If the high-frequency event is triggered again within N seconds, a new calculation time will be generated
    [scenario] search search Lenovo. When users constantly input values, they use anti shake to save request resources
    [scenario] when the window triggers resize, constantly adjusting the size of the browser window will continuously trigger this event. Use anti shake to trigger it only once

    function debounce(fn, delay=500) {
        let timer = null
        return function(){
            if(timer){
                clearInterval(timer)
            }
            timer = setTimeout(()=>{
                fn.apply(this,arguments)
                timer = null
            },delay)
        }
    }
    

    Throttling is triggered by high-frequency events and executed at the same frequency, so throttling will dilute the execution efficiency of the function
    [scenario] mouse clicking triggers mousedown (only triggered once per unit time)
    [scenario] monitor scrolling events, such as whether to slide to the bottom and load more

    function throttle(fn, delay=500){
        let timer = null;
        return function() {
            if(timer){
                return
            }
            timer = setTimeout(()=>{
                fn.apply(fn,arguments)
                timer = null
            },delay)
        }
    }
    
  • Depth comparison

    const obj1 = {
        a: 100, b: {x:100,y:100},c:[1,2,3,4]
    }
    const obj2 = {
        a: 100, b:{x:100,y:100},c:[1,2,3]
    }
    
    function isObject(obj) {
        return typeof obj === 'object' && obj !==null
    }
    
    function isEqual(obj1,obj2) {
        if(!isObject(obj1) || !isObject(ob2)) {
            return obj1 === obj2
        }
        if(obj1 === obj2) {
            return true
        }
        
        const obj1Keys = Object.keys(obj1)
        const obj2Keys = Object.keys(obj2)
        if (obj1Keys.length !== obj2Keys.length){
            return false
        }
        
        for(let key in obj1) {
            const res = isEqual(obj1[key], obj2[key])
            if(!res){
                return false
            }
        }
        return true
    }
    console.log(isEqual(obj1, obj2))
    
  • Array flattening

    Method 1

    function flat(arr) {
        const r = arr.some(a=>{
            return a instanceof Array
        })
        if(!r) {
            return arr
        }
        const newArr = Array.prototype.concat.apply([],arr) //a key
        return flat(newArr)
    }
    

    Method 2

    function flat(arr) {
        return arr.reduce((newArr,arr)=>{
            if(!(arr instanceof Array)) {
                newArr.push(arr)
            }else{
                const newResult = (flat(Array.prototype.concat.apply([],arr))) //a key
                newArr = newArr.concat(newResult)
            }
            return newArr
        },[])
    }
    

Tags: Javascript

Posted by praveenp on Fri, 15 Apr 2022 09:10:32 +0930