What are the data types

Primitive data type

  • The number of digital
  • String string
  • Boolean Boolean
  • Null Null object pointer
  • Undefined undefined
  • Bigint tarsus

Object type [reference data type]

  • Standard common object Object
  • Standard special objects Array, RegExp, Data, Math, Error…
  • Nonstandard special objects Number, String, Boolean…
  • Callable/executable object function

What are the methods of data detection

typeof

  • The typeof return value is always a string.
    • typeof typeof typeof 'nihao'The return result is'string'
  • typeof bullThe return value is'object'
  • typeof functionThe return value'function'
  • typeof nDetect an undeclared variable, return value is'undefined'
  • Detection is performed according to the binary of the underlying storage of the computer [high efficiency]
    • The beginning of 000 represents the object
    • Numbers starting with 1
    • Starting with 010 represents a floating point number (with a decimal point)
    • A string starting from 100
    • 110 starts out as Boolean
    • The beginning of 0000000 represents NULL, which is why null detection is object.
    • – 2 ^ 30 represent undefined

Typeof underlying processing mechanism

instanceof

constructor

object.prototype.toString.call

JS underlying storage mechanism: Heap, Stack memory

  • When the browser loads the render page, it first allocates two blocks of memory from the computer’s memory bar. (Stack memory)

Stack memory (ECStack execution environment stack)

Stack memory function

  • For code to execute
    • At first, global code to be executed forms a global execution context (EC (G)) and is then pushed to the stack
  • Holds declared variables
  • Store raw value types
  • Stores global execution context, function private context, block level private context
    • Global context creation time: open the page, execute global code will be formed, the page will be released when closing, or press F5 refresh, equivalent to delete the previous global context, to generate a new global context.
    • A private context is generated when code is executed into a function or block-level scope, which is released as soon as the function or block-level scope code completes execution. So every time the function executes, it generates a new private context (also known as the live object)

Heap memory

Heap memory function

  • Holds object data type values
  • The built-in API for placing a browser window (global Object) is called GO memory space, such as setTimeout and Alert.

What happens when a variable is created

  • Var Variable = value
    • To create value
      • Raw values are stored directly in stack memory
      • The object value needs to be exported to the heap, creating a space (hexadecimal address) in which to store the key-value pairs of the object, and finally putting the address into the stack memory for importing variables.
    • Declare a variable
      • Stores declared variables in the variable object of the current context
    • The assignment (definition) operation
      • Associate variables with corresponding values (Pointers to procedures)
  • Pay attention to
    • Var a = 13; var a = 13; var a = 13; var a = 13; var a = 13; He creates the a:13 key and corresponding address in GO, and assigns that address to the variable A in VO. We can get the value of A from window.a.
    • VO (let/const/class); VO (let/const/class);
    • A variable without any declaration is equivalent to setting a property on the global variable object (GO).
      var a = 13;
      console.log(a,window.a)/ / 13 13
      let b = 15;
      console.log(b,window.b)// 15 undefined
      d = 15  / / is equal to the window. D
      // Note: In the global context, use a variable, first see if it is VO, if not, see GO, if not, no error is defined.
      Copy the code

Closure scope and browser garbage Collection (GC)

There are two common mechanisms for browser garbage collection

The first type of tag removal (Chrome)

  • When opening up memory (whether stack memory or heap memory), there will be a mark to mark whether they have been referenced, the browser will be in their free time, we will open up memory to iteration and traversal, if there is no reference browser will automatically reclaim it.

Second reference counting Method (IE6~8)

  • Reference counting is similar to tag clearing in that it marks the address as many times it is referenced, and when its reference count is zero, the browser reclaims it when idle.

  • For example,

let obj = { name: 1.age: 12}; // A heap is created to store the key-value pairs
obj = null;  // reassign the variable obj, and the heap will be freed when there is browser free in it
Copy the code

closure

  • Private context: General function (block) in the execution of the code, the browser will automatically make private context for release, but if the current context, a and its associated content (typically a heap memory) are occupied by things outside of the current context that this private context can’t stack release, so that the private in the context of private variables and values are stored.

  • It is the mechanism by which a function execution creates a private context (scope) that protects its private variables from external interference and global variables contamination. We call this mechanism for function execution a closure.

Practical use of closures

  • Closures solve the loop-click button binding event, clicking the button to output the current index

File upload

Small files are based on file streams

  1. Based on file stream
    • Use the Element – UI Upload plugin directly
    beforeUpload(file){
        let {type, size} = file
        if(/(png|git|jpeg|jpg)/i.test(type)){
            this.$message('File format is incorrect')
            retrun false
        }
        if(size>200*1024*1024) {this.$message('File format is incorrect')
            return false}}handleSuccess(result){
        // Data result is returned after the request succeeds
    }
    Copy the code
  2. Based on base64 encoding format
    • FileReader the uploaded file first.
    • Convert it to base64 encoding format
    • Pass the information to the server itself based on AXIOS
    function fileParse(file,type==='base64'){
        return new Promise(resolve= >{
            let fileRead = new FileReader();
            if(type=='base64'){
                fileRead.readAsDataURL(file); 
                }else{
                    fileRead.readAsArrayBuffer(file)
                    }
            fileRead.onload = ev= >{
                 resolve(ev.target.result)
            }
        })
    }
    Copy the code

Large file slice upload and * breakpoint continuation

import SparkMD5 from 'spark-md5'
async changeFile(file){
    if(! file)return
    file = file.raw
    // Use the above method to parse the file into buffer data
    // We will slice the file; To divide a file into several parts (fixed number/fixed size)
    
    // Fixed quantity
    // Each slice has its own part of data and its own name, such as hash-1.mp4, hash-2.mp4, hash-3.mp4...
    let buffer = await fileParse(file,'buffer'),
    spark = new SparkMD5.ArrayBuffer(),
    hash,
    suffix;/ / suffix
    spark.append(buffer)
    hash = spark.end()
    suffix = /\.([0-9a-zA-Z]+)$/i.exec(file.name)[1]
    
    // Create 100 slices
    let partList = [],
    partsize = file.size / 100,
    cur = 0
    for(let i = 0; i<100; i++){
        let item = {
            chunk: file.slice(cur,cur + partsize),
            filename: `${hash}_${i}.${suffix}`
        }
        cur += partsize
        partList.push(item)
    }
    this.partList = partList
    this.hash = hash
    this.fileUpload()
}
// Upload slices
async function fileUpload(){
Create 100 request sets based on 100 slices
    let requestList = [];
    this.partList.forEach((item,index) = >{
        let fn = () = >{
        let formData = new FormData();
            formData.append('chunk',item.chunk)
            formData.append('filename',item.filename)
            return axios.post('url',formData,{headers: {"Content-Type":"multipart/form-data"}}).then(res= >{
                result = res.data
                if(result.code==0) {this.total += 1; // This is the number of uploads
                    // Remove the slices
                    this.partList.splice(index,1)
                }
            })
        }
        requestList.push(fn)  // Set of 100 requests
    }) 
    // Pass: Concurrency (parallel) through ajax.abort() prevents continued upload/serial based on identity (custom variable control does not continue send)
    let i = 0;
    let complete = async() = > {let result = await axios.post('url', {params: {hash:this.hash}})
        result = result.data
        if(result.code ===0) {this.$message('Upload successful')}else{
            this.$message(' ')}}let send =async() = > {if(this.abort) return
        if(i>=requestList.length){
            // It's all done
            complete()
            return
        }
        await requestList[i]()
        i++
        send()
    }
    send()
}
// Pause to continue, break upload
function handleBtn(){
    if(this.btn){
    // Resumable
    this.btn = false// Continue the pause with true false
    this.abort = false
    this.fileUpload()
    }
    // Stop uploading
    this.btn = true
    this.abort = true
}
Copy the code

File download

  1. Based on the blob
    // If you need to download the json file
    function(res.e){
        let blob
        if(e==='json'){
            blob = new Blob ([JSON.stringfy(res.data)])
        }else{
            blob = new Blob([res.data])
        }
        let fileName = decodeURI(escape(res.headers['filename']))
        if('dowload' in document.createElement('a')) {let a = document.createElement('a')
                a.download = fileName
                a.display.style = none
                a.href = URL.createObjectURL(blob)
                document.body.appendChild(a)
                a.click()
                URL.removeObjectURL(a.href)
                document.removeChild(a)
        }else{
                navigator.msSaveBlob(blob)
        }
    }
    Copy the code

Promise

Promise to use

  • New Promise(executable function)
    • It is equivalent to new a class execution, which is synchronous, and the code runs the same as new a function.
    • When a new Promise is made, the executable function will be executed immediately within the Promise. Generally, this function is to put an asynchronous programming code, but non-asynchronous code can also be used.
    • The executable function is passed two arguments, resolve and reject.
  • let p = new Promise(()=>{})
    • P is an instance of Promise
    • Built-in private property
      • PromiseState instance Status Pending Preparation status Disappointing/Resolved Success Status Rejected
      • PromiseValue
    • Public property method promise.prototype
      • then
      • catch
      • Symbol (Symbol. ToStringTag) : ‘Promise’. This is also the object tostring. The prototype. The principle of call (” p “) [object Promise]
  • Execute resolve or reject in an executable to change the state of the instance
  • Once the state changes to regret, resolved or Rejected, it cannot be changed to other states
let p1 = new Promise((resolve,reject) = >{
    resolve('ok') // If this is PromiseState, it will be resolved, and the value of PromiseValue will be OK, or reject
})
Copy the code
  • An instance state change can control one of the two methods in then, with Resolved firing firing the first callback and Reject firing the second. The value of the PromiseValue is passed to the method

        let p = new Promise((resolve,reject) = >{
           resolve('ok')
        }).then((res) = >{
               console.log(res)// 'ok'
           },() = >{})
    Copy the code
  • When the promise status changes from Pending to Resolved or Reject

    • The oncallbacks and onrejectCallback will be stored in a container.
    • Second, verify the current instance state
    • After validation, notify the corresponding callback function to execute. Then
  • let p2 = p1.then(res=>{ console.log(111) },rej=>{})

    • P2 is not equal to p1, and p2 is an instance of p1.then(). It is still pending, and changing its state requires either resolve or reject in the.then() callbacks
  • If our onledCallback and onrejectCallback are not passed, the state will be deferred/passed through to the next correspondence function that should be executed in the same state, internally complementation the default function that implements the effect.

    new Promise ((resolve,reject) = >{
        resolve('ok')
    }).then(null.null).then((res) = >{
        console.log('success',res),
        (reject) = >{
            console.log('failure',reject)
        }
    })
    Copy the code
  • The mechanism of a catch failure is as follows

    Promise.prototype.catch = function(onrejectedCallback) {
        return this.then(null,onrejectedCallback)
    }
    Copy the code
  • Combination of continuous and catch, written in real projects

    new Promise((resolve,reject) = >{
        reject('no')
    }).then(res= >{
        console.log('success',res)
    }).catch(rej= >{
        console.log('failure',rej)
    })
    Copy the code
  • all

    • Let aa = Promise. All ([Promise instance])
      • Require that each item in the array be an instance of promise
      • All returns an instance of promise, which succeeds or fails depending on whether the instance of each item in the array succeeds or fails. If there is a single failure, the return value fails. Aa is only successful if both are successful.
      let a = new Promise((resolve) = >{
          resolve('ok')})let b = new Promise((resolve,reject) = >{
          reject('no')})Promise.all([a,b]).then(res= >{
          console.log(res,'ok')
      }).catch(rej= >{
          console.log(rej,'rej')})Copy the code
    • Whoever knows the state first will end up in the same order as the ardi array
  • Race who knows the status first returns AA for success and failure

Promise output case

new Promise((resolve) = >{
    console.log('promise1')
    resolve()
}).then(() = >{
    console.log('then11')
    new Promise((resolve) = >{
        console.log('promise2')
        resolve()
    }).then(() = >{
        console.log('then21')
    }).then(() = >{
        console.log('then22')
    })
}).then(() = >{
    console.log('then12')})// promise1 then11 promise2 then21 then12 then22
Copy the code
  • Parse the above code
    • The new promise is synchronous, so promise1 is printed first
    • Resolve to change its status to successful, so its first then11 is microtask 1, immediately add EventQueue
    • The second then12, whose state depends on then11, hasn’t finished executing yet, so it’s in webAPI listening to wait.
    • Perform microtask 1 (THEN11), and assign THEN11, promise2 to the interface
    • Resolve state successful, generate microtask 3 immediately, then21,
    • Then22, whose state depends on THEN21, but THEN21 hasn’t been executed yet, so put in webAPI
    • To execute the code, type then21, webAPI microtask 2 comes first, so execute first, output then12 and then22

async await ES7

  • Async is a modifier to a function that controls the return of a Promise instance
    async function fn(){
        return 10
    }
    console.log(fn())  // Return the promise instance in a success state with a value of 10
    Copy the code
    • If an internal execution of the function fails, an instance of promise is returned with a failed state

Add try and catch to async

  • If an exception is caught inside the function, the status is still successful
    let a = async function fn() {
        try {
          console.log(b);
        } catch (e) {
          console.log(e);  // Catch an error
        }
        return 10;
    };
    console.log(a()); // The return status is successful and the value is 10
    Copy the code
  • “Await” is an asynchronous microtask, and the code behind “await” will do whatever it wants, but the code below will pause them as a task and set them in the EventQueue microtask queue.
  • “Await” is usually followed by a Promise instance. If an await is followed by a non-promise instance, the browser changes it to a Promise instance. If an await is followed by a failed instance, the code finishes executing. The following
    async function fn(){
        await 1 // equivalent to await promise.resolve (1)
        await Promise.reject(1)
        console.log(1111) // will not output 1111
    }
    Copy the code

About this

event

  • DOM0; xxx.onxxx = function(){}
  • DOM2; xxx.addEventListener(‘onxxx’,function(){})
    • Bind a method to an event of the current element. When the event is triggered, the browser will execute the bound function. This in the function is the current element object.

Function performs

  • Normal normal function execution, see if there is a function beforepoint, there arepoint“This” is the same as “this”, no, “this” is “window”, strictly undefined.'use strict'
  • Anonymous functions
    • Functional expressionvar fn = function(){console.log(this)} //window
    • Self-executing function(function(x){console.log(this)})(10) //window
    • The callback functionfunction(callback){callback()}// It is usually window, but can be changed by call.
  • This refers to the question
        var x = 3,
        obj = {
            x: 5}; obj.fn = (function () {
        this.x *= ++x; //window x = 12
        return function (y) {
            console.log(this)
            this.x *= ++x + y;  //obj.x = 95
            console.log(x);  //x 13}; }) ();var fn = obj.fn;
    obj.fn(6);
    fn(4); / / 234
    console.log(obj.x, x); / / 95 234
    
    // First the code executes from top to bottom, creating x, obj, obj.fn, executing from the self-executing function, and assigning return to fn
    // obj.fn(6) executes, equivalent to this is obj, and executes the return value
    // fn(4) executes, equivalent to its this is window
    Copy the code