Summary of interview questions (3)-JS

Modular

Modularization splits complex programs into independent modules, which is conducive to reuse and maintenance of
reference

Closures and usage scenarios

Closure: A function that can access and maintain internal variables of other functions

Usage scenarios: callback parameter transfer, setTimeout parameter transfer, ES6 module (similar, not sure about the implementation principle, not sure), result cache

Classes and inheritance

ES5:
Property Definition: Constructor
Method Definition: Prototype Chain
Inheritance: Parasitic Combination Inheritance

function inherit(father, child) {
    
    
    Object.setPrototypeOf(child.prototype, father.prototype)
}

ES6:
class + extends

End of the prototype chain

Function.__proto__ === Function.prototype
Object.prototype = {}

Eventloop

First take the micro task queue, then take the macro task queue, each operation is this step, until the two queues are all processed

Note: process.nextTick>promise.then

new operator

Create an empty object, set the prototype of the object to the prototype of the constructor, execute the constructor, and return the object

this points to

  1. Normal call refers to the global by default
  2. The prefix call points to the immediately following prefix object
  3. call, apply, bindPoint to pass parameters
  4. new Point to return instance
  5. The arrow points to the outer layer of the environment and breaks all the above rules

Throttling and anti-shake

Throttling: Trigger only once within the specified interval.
Anti-shake: continuous trigger only trigger the last time

Garbage collection

Mark clearing: reachability algorithm, marking the first time and clearing unmarked variables for the second time.
Reference count: clearing the variables whose reference number is 0

Ajax prevents browser caching

Ajax.setRequestHeader("If-Modified-Since","0")
Ajax.setRequestHeader("Cache-Control","no-cache")
Add a number after the URL
"nowtime=" + new Date().getTime()
"fresh=" + Math.random()

Event stream

Event flow:
capture phase => target phase => bubbling phase

addEventListenerReceive 3 parameters, the name of the event to be processed, the callback function, whether to process the event in the capture phase

DOM 0Level event: onclickmonitor, multiple monitors cannot be defined, the latter overrides the former
DOM 2Level event: addEventListenermonitor, multiple monitors can be defined, the same function under the same event can only be monitored once

Bubbling first and then capture: By monitoring the capture and bubbling events separately, the execution of the capture is delayed until the bubbling event is executed before the capture event is executed

Event delegation

Listen to the event on the parent node of the event trigger target, and trigger event handlers through event bubbling, thereby uniformly managing similar events

Array deduplication

  • indexOfRecycle
  • Set()
  • ObjectAttributes

Cross-domain

reference

Arrow function

  • Simplify writing, bindingthis
  • Do not own this, arguments, superornew.target
  • Cannot be used as a constructor, it newwill report an error
  • Noprototype

What is webpack used for

webpack is a static module bundler for modern JavaScript applications. When webpack processes an application, it recursively builds a dependency graph, which contains every module needed by the application, and then packs all these modules into one or more bundles

What is on-demand loading

The corresponding function is loaded when the user triggers an action. The triggered action depends on the specific business scenario, including but not limited to the following situations: mouse click, text input, scroll bar pull, mouse movement, window size change, etc. The loaded file can be JS, image, CSS, HTML, etc.

Tell me what is virtual dom

Use JavaScript object structure to represent the structure of the DOM tree; then use this tree to build a real DOM tree, insert it into the document, and rebuild a new object tree when the state changes. Then compare the new tree with the old tree, record the differences between the two trees and apply the recorded differences to the real DOM tree constructed, and the view is updated. Virtual DOM is essentially a cache between JS and DOM

The difference between typeof, instanceof, isPrototypeOf

typeof: Check the type of the parameter, the value is one of the JSbasic data types, nullfor object
instanceof: check the relationship between the object and the class, check whether the prototype of the right parameter is in the prototype chain of the left parameter
isPrototypeOf: check the relationship between the object and the object, check whether the calling object is in In the prototype chain of the passed parameter object

The difference between preloading and lazy loading

Pre-loading: load pictures in advance, users can read them directly from the cache when viewing them.
Lazy loading: slow loading pictures and load them when users need to view them.

The two behaviors are opposite, one is to optimize user experience and increase server pressure. One is to optimize page performance and reduce server pressure

The difference between mouseover and mouseenter

mouseover: Move the mouse into the target element will trigger, move in or out between the child element and the target element will trigger again
mouseenter: trigger when the mouse moves into the target element, move in or out between the child element and the target element will not trigger again

The difference between bind, apply, call

Both are used to modify the internal thispointer of the function .
bindUse the target function to generate a new function
applyand execute the target function immediately. The parameter passing method is the array
callto execute the target function immediately, and the parameter passing method is sequential parameter passing.

JS position difference

clientHeight: The height of the visible area, excluding the border and scroll bar
offsetHeight: the height of the visible area, including the border and scroll bar
scrollHeight: the height of all areas, including the part hidden by scrolling
scrollTop: the height
offsetTopthat is hidden after scrolling : the current element is away from the top padding of offsetParent The distance offsetParentis the nearest element with the positioning attribute, otherwise it is body. When is bodythe time, it includes borders and margins.

== and ===, and the difference between Object.is

==: Compare values ​​after type conversion
===: Compare types and values, and compare addresses when referencing data types, NANnot equal to itself
Object.is: Except for being NANequal to itself +0 !== -0, everything else is ===consistent with the behavior

The difference between timer and requestAnimationFrame

setTimeout: Trigger the callback after the specified time, only trigger one time
setInterval: Trigger the callback after the specified time, trigger multiple times
requestAnimationFrame: solve the problem of inaccurate timer trigger animation time, the browser automatically calls the callback according to the display refresh frequency and optimizes the call

Due to its setIntervalown shortcomings, using the setTimeoutimplemented setIntervalfunctions can ensure that the interval between two calls and each callback will not be cancelled

Implement deep copy function

function deepCopy(obj) {
    
    
    if (obj && typeof obj === 'object') {
    
    
        let res = obj instanceof Array ? [] : {
    
    }
        for (let item of Object.keys(obj)) res[item] = deepCopy(obj[item])
        return res
    }
    return obj
}

Implement the once function

function once(fn, ...rest) {
    
    
    let lock = 0
    return function () {
    
    
        if (!lock++) return fn(...rest)
    }
}

Implement attribute monitoring

let obj = {
    
    
    _name: 66
}
Object.defineProperty(obj, 'name', {
    
    
    set(v) {
    
    
        this._name = v
    },
    get() {
    
    
        return this._name
    }
})
let obj = new Proxy({
    
    }, {
    
    
    set(target, p, value) {
    
    
        target[p] = value
    },
    get(target, p) {
    
    
        return target[p]
    }
})

Implement private variables

let obj = {
    
    
    getName: (function () {
    
    
        let name = 'Soraka'
        return function () {
    
    
            return name
        }
    })()
}

Implement the bind function

Function.prototype.Bind = function (target) {
    
    
    let that = this
    return function (...rest) {
    
    
        that.apply(target, rest)
    }
}

Achieve full arrangement

function permutate(str) {
    
    
    if (str.length === 1) return [str]
    let res = []
    for (let i = 0; i < str.length; i++) {
    
    
        let list = permutate(str.substring(0, i) + str.substring(i + 1))
        list.forEach(val => res.push(str[i] + val))
    }
    return res
}

Guess you like

Origin blog.csdn.net/weixin_44844528/article/details/105824236