Read a lot of JS books and tutorials, tend to blur the focus, this article will do a sort, will be JS in the heavy and difficult to sum up.

The article is divided into two parts. The first part is the basic knowledge, the second part is the advanced knowledge.Copy the code

# Variable types and calculations

Quotes:

  1. The difference between value types and reference types

  2. What types can Typeof determine?

  3. When do I use ===?

  4. Handwritten deep copy

Variable types

  • Value types
  • Reference types

Value types

let a = 100
let b = a
a = 200
console.log(b) / / 100
Copy the code

Reference types

let a = { age: 20 }
let b = a
b.age = 21
console.log(a.age) / / 21
Copy the code

Analysis:

A variable of the value type is assigned with a copy of the value, so the two variables are independent of each other.

The variable name of the reference type points to a memory address, and the real object is stored in the memory that the memory address points to (the heap). When a variable is assigned to let b = a, b will also point to the same chunk of memory that A points to. Both variables actually point to the same object.

Common value types:

const s = 'abc' / / string
const n = 100 / / digital
const b = true / / a Boolean
const s = Symbol('s') // Symbol
Copy the code

Common reference types:

const obj = { x: 100 } / / object
const arr = ['a'.'b'.'c'] / / array
const n = null // Empty, special reference type, pointer to an empty address
function fn() {}Function, special reference type, but not used to store data, so there is no such thing as "copy, copy function"
Copy the code

The typeof operator

  • Identify all value types
  • Identify the function
  • Determine if it is a reference type (cannot be subdivided)

Identify all value types

let a                       typeof a // undefined
const s = 'abc'             typeof a // string
const n = 100               typeof n // number
const b = true              typeof b // boolean
const s = Symbol('s')       typeof s // symbol
Copy the code

Identify the function

typeof console.log // function
typeof function () {}// function
Copy the code

Determine if it is a reference type (cannot be subdivided)

typeof null // object
typeof ['a'.'b'] // object
typeof { x: 100 } // object
Copy the code

Deep copy

/** * deep copy */
const obj1 = {
    age: 20.name: 'xxx'.address: {
        city: 'beijing'
    },
    arr: ['a'.'b'.'c']}const obj2 = deepClone(obj1)
obj2.address.city = 'shanghai'
obj2.arr[0] = 'a1'
console.log(obj1.address.city)
console.log(obj1.arr[0])

/** * deep copy *@param {Object} Obj The object to copy */
function deepClone(obj = {}) {
    if (typeofobj ! = ='object' || obj == null) {
        // obj is null, or is not an object or array
        return obj
    }

    // Initialize the result
    let result
    if (obj instanceof Array) {
        result = []
    } else {
        result = {}
    }

    for (let key in obj) {
        // Ensure that key is not an attribute of the stereotype
        if (obj.hasOwnProperty(key)) {
            // Recursive call!!
            result[key] = deepClone(obj[key])
        }
    }

    // Return the result
    return result
}

Copy the code

Variable calculation

Type conversion:

  • String splicing
  • = =
  • If statements and logical operations

String splicing

const a = 100 + 10 / / 110
const b = 100 + '10' / / '10010'
const c = true + '10' // 'true10'
Copy the code

= =

100= ='100' // true
0= =' ' // true
0= =false // true
false= =' ' // true
null= =undefined // true
Copy the code
== null == nullCopy the code
const obj = { x: 100 }
if (obj.a == null) {}// Equivalent to:
// if (obj.a === null || obj.a === undefined) { }
Copy the code

If statements and logical operations

  • The TRULY variable:!! A === true

  • Services Variable:!! A === false variable

Truly variable

!!!!!1 // true!!!!! {}// true
Copy the code

Falsely variable

!!!!!0 // false!!!!!null // false!!!!!' ' // false!!!!!undefined // false!!!!!NaN // false!!!!!false // false
Copy the code

Example 1: the if statement

/ / truly variables
const a = true
if (a) {
    // ...
}
const b = 100
if (b) {
    // ...
}

/ / falsely variables
const c = ' '
if (c) {
    // ...
}

const d = null
if (d) {
    // ...
}

let e
if (e) {
    // ...
}
Copy the code

Example 2: Logical judgment

console.log(10 && 0) / / 0
console.log(' ' || 'abc') // 'abc'
console.log(!window.abc) // true
Copy the code

# Prototype and prototype chain

Quotes:

  1. How do I determine if a variable is an array?
  2. Write a simple jQuery with plug-ins and extensibility in mind.
  3. How to understand the prototypical nature of class?

Knowledge:

  1. The class and inheritance
  2. Type Check instanceof
  3. Prototype and prototype chain

class

  • constructor
  • attribute
  • methods

Example:

/ / class
class Student {
    constructor(name, number) {
        this.name = name
        this.number = number
        // this.gender = 'male'
    }
    sayHi() {
        console.log(Name of `The ${this.name}Student id,The ${this.number}`)
        // console.log(
        // 'name' + this.name + ', student id '+ this.number
        // )
    }
    // study() {
    // }
}

// Through the class new object/instance
const xialuo = new Student('charlotte'.100)
console.log(xialuo.name)
console.log(xialuo.number)
xialuo.sayHi()

const madongmei = new Student('Ma Dongmei'.101)
console.log(madongmei.name)
console.log(madongmei.number)
madongmei.sayHi()
Copy the code

inheritance

  • extends
  • super
  • Extend or override methods
/ / parent class
class People {
    constructor(name) {
        this.name = name
    }
    eat() {
        console.log(`The ${this.name} eat something`)}}/ / subclass
class Student extends People {
    constructor(name, number) {
        super(name)
        this.number = number
    }
    sayHi() {
        console.log(Name of `The ${this.name}Student idThe ${this.number}`)}}/ / subclass
class Teacher extends People {
    constructor(name, major) {
        super(name)
        this.major = major
    }
    teach() {
        console.log(`The ${this.name}professorThe ${this.major}`)}}/ / instance
const xialuo = new Student('charlotte'.100)
console.log(xialuo.name)
console.log(xialuo.number)
xialuo.sayHi()
xialuo.eat()

/ / instance
const wanglaoshi = new Teacher('Miss Wang'.'Chinese')
console.log(wanglaoshi.name)
console.log(wanglaoshi.major)
wanglaoshi.teach()
wanglaoshi.eat()
Copy the code

Type Check instanceof

xialuo instanceof Student // true
xialuo instanceof People // true
xialuo instanceof Object // true

[] instanceof Array // true
[] instanceof Object // true
{} instanceof Object // true
Copy the code

The prototype

// class is a function
typeof People // 'function'
typeof Student // 'function'

Implicit and explicit archetypes
console.log(xialuo.__proto__) // Implicit prototype
console.log(Student.prototype) // Explicit prototype
console.log(xialuo.__proto__ === Student.prototype) // true
Copy the code

Prototype relationship

  • Each class has an explicit prototype prototype
  • Each instance has an implicit prototype __proto__
  • The instance’s __proto__ points to the prototype corresponding to the class

Schematic diagram:

Prototype-based execution rules

  • Gets the attribute xialuo.name or executes the method xialuo.sayhi()
  • First look in its own properties and methods
  • If it is not found, __proto__ automatically looks for it in.

Prototype chain

console.log(Student.prototype.__proto__)
console.log(People.prototype)
console.log(People.prototype === Student.prototype.__proto__) // true
Copy the code

Schematic diagram

Examples:

How do I determine if a variable is an array?

a instanceof Array
Copy the code

Write a simple jQuery with plug-ins and extensibility in mind.

class jQuery {
    constructor(selector) {
        const result = document.querySelectorAll(selector)
        const length = result.length
        for (let i = 0; i < length; i++) {
            this[i] = result[i]
        }
        this.length = length
        this.selector = selector
    }
    get(index) {
        return this[index]
    }
    each(fn) {
        for (let i = 0; i < this.length; i++) {
            const elem = this[i]
            fn(elem)
        }
    }
    on(type, fn) {
        return this.each(elem= > {
            elem.addEventListener(type, fn, false)})}// Extend many DOM apis
}

/ / the plugin
jQuery.prototype.dialog = function (info) {
    alert(info)
}

// Make the wheel
class myJQuery extends jQuery {
    constructor(selector) {
        super(selector)
    }
    // Extend your methods
    addClass(className){}style(data){}}// const $p = new jQuery('p')
// $p.get(1)
// $p.each((elem) => console.log(elem.nodeName))
// $p.on('click', () => alert('clicked'))

Copy the code

How to understand the prototypical nature of class?

  • Diagrams of prototypes and prototype chains
  • Execution rules for properties and methods

# scope and closure

Quotes:

  • How to value this in different application scenarios?
  • Handwritten bind
  • The application scenarios of closures in actual development are illustrated with examples
  • Create 10 A labels and pop up the corresponding serial number when clicked

Knowledge:

  • Scope and free variables
  • closure
  • this

scope

classification

  • Global scope
  • Function scope
  • Block-level scopes (new in ES6)
// ES6 block-level scope if (true) {let x = 100 // Block-level scope is triggered only when ES6 features such as let or const are used} console.log(x) // an error is reportedCopy the code

Free variables

  • A variable is not defined in the current scope, but is used
  • Work your way up, layer by layer, until you find it

closure

  • The special case of scope application has two manifestations:
  • If the function is passed as an argument
  • The function is returned as the return value

Function as argument

// The function is passed as an argument
function print(fn) {
    const a = 200
    fn()
}
const a = 100
function fn() {
    console.log(a)
}
print(fn) / / 100
Copy the code

Function as the return value

// function as return value
function create() {
    const a = 100
    return function () {
        console.log(a)
    }
}

const fn = create()
const a = 200
fn() / / 100
Copy the code
All free variable lookups are found in the function definition, in the parent scope, not in the execution place!!Copy the code

this

  1. As a general function
  2. Use call, apply, bind
  3. Called as an object method
  4. Called in the class method
  5. Arrow function
The value of this is determined when the function is executed, not when the function is defined. This principle applies to the above five cases.Copy the code

Example 1: Ordinary functions and this in Call, apply, and bind

function fn1() {
    console.log(this)
}

fn1() // window

fn1.call({ x: 100 }) // { x :100 }

const fn2 = fn1.bind({ x: 200 })
fn2() // { x : 200 }
Copy the code

Note: For the differences between call, apply, and bind, see JavaScript for call(), apply(), and bind()

Example 2: This in the object method

const zhangsan = {
    name: 'Joe'.sayHi() {
        // This is the current object
        console.log(this)},wait() {
        setTimeout(function () {
            // this === window
            console.log(this)}}}Copy the code

Example 3: This in the arrow function

const lisi = {
    name: 'bill'.sayHi() {
        // This is the current object
        console.log(this)},wait() {
        setTimeout(() = > {
            // This is the current object
            console.log(this)}}}Copy the code

Example 4: This in class

class People {
    constructor(name) {
        this.name = name
        this.age = 20
    }
    sayHi() {
        console.log(this)}}const zhangsan = new People('Joe')
zhangsan.sayHi() / / zhangsan object
Copy the code

Examples:

1. How to value different application scenarios of this?

    1. As a general function
    1. Use call, apply, bind
    1. Called as an object method
    1. Called in the class method
    1. Arrow function

2. Write bind by hand

The bind / / simulation
Function.prototype.bind1 = function () {
    // Split the parameters into arrays
    const args = Array.prototype.slice.call(arguments)

    // Get this (first item of array)
    const t = args.shift()

    // fn1.bind(...) The fn1
    const self = this

    // Return a function
    return function () {
        return self.apply(t, args)
    }
}

/* fn1.__proto__ === Function.prototype // true */

function fn1(a, b, c) {
    console.log('this'.this)
    console.log(a, b, c)
    return 'this is fn1'
}

const fn2 = fn1.bind1({ x: 100 }, 10.20.30)
const res = fn2()
console.log(res)
Copy the code

3. The application scenarios of closures in actual development are illustrated with examples

  • Hidden data
  • Such as a simple cache tool
// Closures hide data and only provide apis
function createCache() {
    const data = {} // The data in the closure is hidden from outside access
    return {
        set: function (key, val) {
            data[key] = val
        },
        get: function (key) {
            return data[key]
        }
    }
}

const c = createCache()
c.set('a'.100)
console.log(c.get('a'))
Copy the code

4. Create 10 tabs and pop up the corresponding serial number when you click

Error example: ❎

// Create 10 "A" tags. Click on them to pop up the corresponding serial number
let i, a
for (i = 0; i < 10; i++) {
    a = document.createElement('a')
    a.innerHTML = i + '<br>'
    a.addEventListener('click'.function (e) {
        e.preventDefault()
        alert(i) // I is global scope
    })
    document.body.appendChild(a)
}
Copy the code

Correct example: ✅

// Create 10 "A" tags. Click on them to pop up the corresponding serial number
let a
for (let i = 0; i < 10; i++) {
    a = document.createElement('a')
    a.innerHTML = i + '<br>'
    a.addEventListener('click'.function (e) {
        e.preventDefault()
        alert(i) // I is the block-level scope
    })
    document.body.appendChild(a)
}
Copy the code

Note: If you change let I = 0 for the for loop to var I = 10 in the correct example above, the result is the same as in the incorrect example because var defines a global variable.


# asynchronous

Quotes:

  1. What is the difference between synchronous and asynchronous?
  2. Handwriting loads an image with a promise
  3. What are the scenarios where asynchrony is used at the front end?
  4. Read the following code:
console.log(1)
setTimeout(function () {
    console.log(2)},1000)
console.log(3)
setTimeout(function () {
    console.log(4)},0)
console.log(5)
Copy the code

Question: What was the order in which the numbers were printed in the previous code? This is explained at the end of this section.

Knowledge:

  • Single threaded and asynchronous
  • Application scenarios
  • The callback hell and Promise

Single threaded and asynchronous

  • JS is a single-threaded language that can only do one thing at a time
  • Browsers and NodeJS already support JS to start processes, such as Web workers
  • JS and DOM rendering share the same thread because JS can modify the DOM structure
  • Do not get stuck when waiting (network request, scheduled task)
  • Need the asynchronous
  • Callback function form

Asynchrony and synchronization

// Async 100 300 200
console.log(100)
setTimeout(function () {
    console.log(200)},1000)
console.log(300)

// Synchronize 100 200 300
console.log(100)
alert(200)
console.log(300)
Copy the code
Js is a single-threaded language. Asynchrony does not block code execution. Synchronization blocks code execution.Copy the code

Application scenarios

  • Web requests, such as Ajax, image loading
  • A scheduled task, such as setTimeout

Ajax:


// start end data1
console.log('start')
$.get('./data1.json'.function (data1) {
    console.log(data1)
})
console.log('end')
Copy the code

Image loading:

// start end loaded
console.log('start')
let img = document.createElement('img')
img.onload = function () {
    console.log('loaded')
}
img.src = '/xxx.jpg'
console.log('end')
Copy the code

Timer:

/ / 100 300 200
console.log(100)
setTimeout(function () {
    console.log(200)},1000)
console.log(300)

/ * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * /

// 100 300 200 200 200...
console.log(100)
setInterval(function () {
    console.log(200)},1000)
console.log(300)
Copy the code

Callback hell

$.get(url1, (data1) = > {
    console.log(data1)

    $.get(url2, (data2) = > {
        console.log(data2)

        $.get(url3, (data3) = > {
            console.log(data3)
        })
    })
})
Copy the code

Promise

Promise is primarily used to address the problem of too many nested callbacks.

function getData(url) {
    return new Promise((resolve, reject) = > {
        $.ajax({
            url,
            success(data) {
                resolve(data)
            },
            error(err) {
                reject(err)
            }
        })
    })
}

const url1 = '/data1.json'
const url2 = '/data2.json'
const url3 = '/data3.json'

getData(url1).then(data1= > {
    console.log(data1)
    return getData(url2)
}).then(data2= > {
    console.log(data2)
    return getData(url3)
}).then(data3= > {
    console.log(data3)
}).catch(err= > console.error(err))
Copy the code

Examples:

1. What is the difference between synchronous and asynchronous?

Asynchrony does not block code execution, synchronization does.

2. Load an image by hand with a promise

function loadImg(src) {
    const p = new Promise((resolve, reject) = > {
        const img = document.createElement('img')
        img.onload = () = > {
            resolve(img)
        }
        img.onerror = () = > {
            const err = new Error('Image load failed${src}`)
            reject(err)
        }
        img.src = src
    })
    return p
}

const url1 = '1.jpg'
const url2 = '2.jpg'

loadImg(url1).then(img1= > {
    console.log(img1.width)
    return img1 // then returns a normal object and executes the next THEN immediately
}).then(img1= > {
    console.log(img1.height)
    return loadImg(url2) // then returns a new promise instance
                         // The next THEN is executed after the new promise state changes
}).then(img2= > {
    console.log(img2.width)
    return img2
}).then(img2= > {
    console.log(img2.height)
}).catch(ex= > console.error(ex))

Copy the code
Note: If a new promise is returned in then, the next level of THEN will be executed after the new promise state changes. If any other value is returned, the next level then is executed immediatelyCopy the code

3. What are the front-end asynchronous scenarios?

  • Web requests, such as Ajax, image loading
  • A scheduled task, such as setTimeout

4. Read the next piece of code

console.log(1)
setTimeout(function () {
    console.log(2)},1000)
console.log(3)
setTimeout(function () {
    console.log(4)},0)
console.log(5)
Copy the code

Q: What was the order in which the numbers were printed in the previous code?

A: 1, 3, 5, 4, 2


#DOM

Quotes:

  1. What kind of data structure is DOM?
  2. Common apis for DOM manipulation
  3. Attr and property
  4. Insert multiple DOM nodes at once for performance reasons

Knowledge:

  • Nature of the DOM
  • DOM node operation
  • DOM structure manipulation
  • DOM performance

Nature of the DOM

The DOM is essentially a tree, parsed from an HTML file.

DOM node operation

  • Get DOM node
  • poperty
  • attribute

Get DOM node

const div1 = document.getElementById('div1')
console.log('div1', div1)

const divList = document.getElementsByTagName('div') / / collection
console.log('divList.length', divList.length)
console.log('divList[1]', divList[1])

const containerList = document.getElementsByClassName('container') / / collection
console.log('containerList.length', containerList.length)
console.log('containerList[1]', containerList[1])

const pList = document.querySelectorAll('p')
console.log('pList', pList)

const pList = document.querySelectorAll('p')
const p1 = pList[0]
Copy the code

poperty

/ / property form
p1.style.width = '100px'
console.log(p1.style.width)
p1.className = 'red'
console.log(p1.className)
console.log(p1.nodeName)
console.log(p1.nodeType) / / 1
Copy the code

attribute

// attribute
p1.setAttribute('data-name'.'imooc')
console.log(p1.getAttribute('data-name'))
p1.setAttribute('style'.'font-size: 50px; ')
console.log(p1.getAttribute('style'))
Copy the code
Property and attribute: Property modifies the attributes of an object, but is not reflected in the HTML structure. Attribute modifies HTML attributes and changes the HTML structure. Both have the potential to cause DOM re-rendering.Copy the code

DOM structure manipulation

  • A node is added or inserted
  • Gets the parent element, gets the list of child elements
  • Deleting child elements

A node is added or inserted

const div1 = document.getElementById('div1')
const div2 = document.getElementById('div2')

// Create a node
const newP = document.createElement('p')
newP.innerHTML = 'this is newP'
// Insert the node
div1.appendChild(newP)

// Move the node
const p1 = document.getElementById('p1')
div2.appendChild(p1)
Copy the code

Gets the parent element, gets the list of child elements

// Get the parent element
console.log(p1.parentNode)

// Get the list of child elements
const div1ChildNodes = div1.childNodes
console.log(div1.childNodes)
const div1ChildNodesP = Array.prototype.slice.call(div1.childNodes).filter(child= > {
    if (child.nodeType === 1) {
        return true
    }
    return false
})
console.log('div1ChildNodesP', div1ChildNodesP)
Copy the code
Note: the childNodes property of a node node returns all direct childNodes, including the '#text' node.Copy the code

Deleting child elements

div1.removeChild(div1ChildNodesP[0])
Copy the code

DOM performance

  • DOM manipulation is expensive, so avoid frequent DOM manipulation
  • Cache DOM queries
  • Change the frequent operation to a one-time operation

DOM manipulation is expensive, so avoid frequent DOM manipulation

// DOM query results are not cached
for (let i = 0; i < document.getElementsByTagName('p').length; i++) {
    // For each loop, length is computed and DOM queries are performed frequently
}
Copy the code

Cache DOM queries

const pList = document.getElementsByTagName('p')
const length = pList.length
for (let i = 0; i < length; i++) {
    // Cache length, only one DOM query
}
Copy the code

Change the frequent operation to a one-time operation

const list = document.getElementById('list')

// Create a document fragment that is not yet inserted into the DOM structure
const frag = document.createDocumentFragment()

for (let i = 0; i < 20; i++) {
    const li = document.createElement('li')
    li.innerHTML = `List item ${i}`

    // Insert the document fragment first
    frag.appendChild(li)
}

// Insert into the DOM structure
list.appendChild(frag)

console.log(list)
Copy the code

Examples:

1. What data structure is DOM?

A: Tree (DOM tree)

2. Common APIS for DOM manipulation

A: DOM node operations, DOM structure operations, attributes and properties

3. Attr and property

A: Property modifies the attributes of the object, but is not reflected in the HTML structure; Attribute modifies HTML attributes and changes the HTML structure. Both have the potential to cause DOM re-rendering.

4. Insert multiple DOM nodes at a time to consider performance

const list = document.getElementById('list')

// Create a document fragment that is not yet inserted into the DOM structure
const frag = document.createDocumentFragment()

for (let i = 0; i < 20; i++) {
    const li = document.createElement('li')
    li.innerHTML = `List item ${i}`

    // Insert the document fragment first
    frag.appendChild(li)
}

// Insert into the DOM structure
list.appendChild(frag)
Copy the code

#BOM

Quotes:

  1. How do I identify the browser type?
  2. Analyze and disassemble parts of the URL

Knowledge:

  • navigator
  • screen
  • location
  • history

The navigator and screen

// navigator
const ua = navigator.userAgent
const isChrome = ua.indexOf('Chrome')
console.log(isChrome)

// screen
console.log(screen.width)
console.log(screen.height)
Copy the code

The location and history

// location
console.log(location.href)
console.log(location.protocol)
console.log(location.pathname)
console.log(location.search)
console.log(location.hash)

// history
history.back()
history.forward()
Copy the code

See above.


# events

Quotes:

  1. Write a generic event listener function
  2. Describes the flow of event bubbling
  3. Infinite drop-down list of pictures, how to listen to each click of the picture?

Knowledge:

  • event
  • The event bubbling
  • The event agent

event

const btn = document.getElementById('btn1')
btn.addEventListener('click'.event= > {
    console.log('clicked')})// A generic binding function
function bindEvent(elem, type, fn) {
    elem.addEventListener(type, fn)
}

const a = document.getElementById('link1')
bindEvent(a, 'click'.e= > {
    e.preventDefault() // Prevent default behavior
    alert('clicked')})Copy the code

The event bubbling

<body>
    <div id="div1">
        <p id="p1">The activation</p>
        <p id="p2">cancel</p>
        <p id="p3">cancel</p>
        <p id="p4">cancel</p>
    </div>
    <div id="div2">
        <p id="p5">The activation</p>
        <p id="p6">cancel</p>
    </div>
</body>
Copy the code
const p1 = document.getElementById('p1')
const body = document.body
bindEvent(p1, 'click'.e= > {
    e.stopPropagation() // Comment out this line to experience the bubbling of events
    alert('activate')
})

bindEvent(body, 'click'.e= > {
    alert('cancel')})Copy the code

The event agent

  • The code is simple
  • Reduce browser memory usage
  • But don’t abuse it
<div id="div1">
    <a href="#">a1</a>
    <a href="#">a2</a>
    <a href="#">a3</a>
    <a href="#">a4</a>
</div>
<button>Click to add an A TAB</button>
Copy the code
const div1 = document.getElementById('div1')
div1.addEventListener('click'.e= > {
    const target = e.target
    if (e.nodeName === 'A') {
        alert(target.innerHTML)
    }
})
Copy the code

Generic event binding

function bindEvent(elem, type, selector, fn) {
    if (fn == null) {
        fn = selector
        selector = null
    }
    elem.addEventListener(type, event= > {
        const target = event.target
        if (selector) {
            // Proxy binding
            if (target.matches(selector)) {
                fn.call(target, event)
            }
        } else {
            // Plain binding
            fn.call(target, event)
        }
    })
}

// Plain binding
const btn1 = document.getElementById('btn1')
bindEvent(btn1, 'click'.function (event) {
    // console.log(event.target) // Gets the triggered element
    event.preventDefault() // Prevent default behavior
    alert(this.innerHTML)
})

// Proxy binding
const div3 = document.getElementById('div3')
bindEvent(div3, 'click'.'a'.function (event) {
    event.preventDefault()
    alert(this.innerHTML)
})
Copy the code

Examples:

1. Write a generic event listener

See general Event Binding above

2. Describe the event bubbling process

  • Based on DOM tree structure
  • Events bubble up the trigger element
  • Application scenario: Proxy

3. Infinite drop-down list of pictures, how to monitor the click of each picture?

  • The event agent
  • Get the trigger element with e.target
  • Matches is used to determine whether it is a trigger

#Ajax

Quotes:

  1. Write a simple Ajax by hand
  2. Common implementations across domains

Knowledge:

  • XMLHttpRequest
  • Status code
  • Cross-domain: Same-origin policy, cross-domain solution

XMLHttpRequest

// GET
const xhr = new XMLHttpRequest()
xhr.open('GET'.'/api'.true) // true: asynchronous
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            alert(xhr.responseText)
        }
    }
}
xhr.send(null)

/ * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * /
// POST
const xhr = new XMLHttpRequest()
xhr.open('POST'.'/login'.true) // true: asynchronous
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            alert(xhr.responseText)
        }
    }
}

const postData = {
    username: 'zhangsan'.password: '123'
}
xhr.send(JSON.stringify(postData))
Copy the code

Status code

xhr.readystatechange

  • 0 – (uninitialized) The send method has not been called
  • 1 – (load) The send() method has been called and the request is being sent
  • 2 – (load done) The send() method is complete and all responses have been received
  • 3 – (Interaction) Parsing the response content
  • 4 – (Done) The response content is parsed and can be called on the client side

xhr.status

  • 2xx – Indicates that the request was successfully processed, such as 200
  • 3xx – Redirection is required, for example, 301 302 304
  • 4xx – Client request error, such as 404 403
  • 5xx – Server side error

Cross-domain: Same-origin policy, cross-domain solution

  • What is Cross-domain (Same Origin Policy)
  • JSONP
  • CORS (Server support)

The same-origin policy

  • When making an Ajax request, the browser requires that the current web page and the server must be of the same origin (security)
  • Cognate: the protocol, domain name, and port must be the same.
  • As the front:http://a.com:8080; Server:https://b.com/api/xxx

Loading images, CSS JS can ignore the same origin policy

  • <img rc= cross-domain image address />
  • <link href= cross-domain CSS address />
  • <script SRC = cross-domain js address ></script>
  • <img />Can be used for statistics, can use third party statistics services
  • <link /> <script>CDN can be used, CDNn is generally an outfield
  • <script>It can realize the json

Cross domain

  • All cross-domains must be allowed and coordinated by the server
  • Without the permission of the server to achieve cross-domain, indicating that the browser has vulnerabilities, danger signals

JSONP

  • Visit Baidu.com, does the server must return an HTML file?
  • The server can dynamically concatenate data as long as it conforms to HTML format requirements
  • In the same way<script src="http://baidu.com/getData.js">
  • <script>Cross-domain restrictions can be bypassed
  • The server can dynamically concatenate data back at will
  • so<script>You can get cross-domain data if the server is willing to return it
<script>
window.callback = function(data){
    this.console.log(data)
}
</script>
<script src="http://www.baidu.com/getData.js"></script>
<! Callback ({x:100, y:200})-->
Copy the code

JQuery implementation json

$.ajax({
    url: 'http://baicu.com/x-origin.json'.dataType: 'jsonp'
    jsonpCallback: 'callback'.success: function (data) {
        console.log(data)
    }
})
Copy the code

CORS – The server sets HTTP headers

// The second parameter is allowed to cross the domain name, say it is not recommended to directly write '*'
response.setHeader('Access-Control-Allow-Origin'.'http://baidu.com');
response.setHeader('Access-Control-Allow-Headers'.'X-Requested-With');
response.setHeader('Access-Control-Allow-Methods'.'PUT,POST,GET,DELETE,OPTIONS');

// Receives cross-domain cookies
response.setHeader('Access-Control-Allow-Credentials'.'true');
Copy the code

Examples:

Write a simple Ajax by hand

// Regular form
function ajax(url, successFn) {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, true) // true: asynchronous
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                successFn(xhr.responseText)
            }
        }
    }
    xhr.send(null)}/ / Promise
function ajax(url) {
    const p = new Promise((resolve, reject) = > {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(
                        JSON.parse(xhr.responseText)
                    )
                } else if (xhr.status === 404 || xhr.status === 500) {
                    reject(new Error('404 not found'))
                }
            }
        }
        xhr.send(null)})return p
}

const url = '/data/test.json'
ajax(url)
.then(res= > console.log(res))
.catch(err= > console.error(err))
Copy the code

2. Common implementations across domains

  • JSONP
  • CORS

# storage

Quotes:

  • Describes the differences between cookie, localStorage, and sessionStorage

knowledge

  • cookie
  • LocalStorage and sessionStorage

cookie

  • It is used for browser and server communication
  • Is “borrowed” to local storage
  • availabledocument.cookie= '... 'To modify the

The disadvantage of the Cookie

  • The maximum storage size is 4KB
  • HTTP requests must be sent to the server to increase the amount of requested data
  • Can only usedocument.cookie='... 'To revise it. It’s too crude

LocalStorage and sessionStorage

  • HTML5 is specifically designed for storage and can hold up to 5M
  • Easy to use API, setItem, getItem
  • Will not be sent out with the HTTP request.
  • LocalStorage data is permanently stored unless deleted by code or manually
  • SessionStorage data only exists in the current session and is cleared when the browser is closed
  • Generally use localStorage will be more

Examples:

Describes the differences between cookie, localStorage, and sessionStorage

  • capacity
  • API for ease of use
  • Whether to send an HTTP request

# Development environment

Knowledge:

  • git
  • A debugging tool
  • caught
  • webpack
  • babel
  • Common Linux Commands

git

  • The most commonly used code versioning tool
  • Large projects require collaboration with many people, and you must take Git
  • Git comes with the Mac OS. For Windows, you can download and install git from the official website
  • Git server common github coding.net, etc
  • Large companies will build their own Intranet Git services

Git git

git add .
git checkout xxx
git commit -m "xxx"
git push origin master
git pull origin master
git diff/git diff filename
git log
git show commit_id
git branch
git checkout -b xxx/git checkout xxx
git fetch
git merge xxx
git stash
git stash pop
Copy the code

List of common Git commands

Chrome Debugger

  • elements
  • console
  • debugger
  • network
  • application

caught

  • Mobile terminal H5 page, view network requests, need to use the package tool

  • Windows is usually used with Fiddler

  • Mac OS uses Charles

  • Cell phones and computers together with a LAN

  • Proxy the phone to the computer

  • You can browse the web to find the bag

  • Viewing network Requests

  • Site agent

  • https

Charles Mobile phone agent Settings

Webpack and Babel

The volume is too large, omitted here.

Linux command

  • The company’s online machines are usually Linux (see Aliyun)
  • The test machine also needs to be consistent with Linux
  • There is a problem with the test machine or the on-line machine, and the local machine cannot reproduce, so it needs to be checked

# Runtime environment

  • The runtime environment is the browser (with nodeJS on the server)
  • Download the web code and render the page, executing several jS
  • Make sure your code is stable and efficient in the browser

knowledge

  • Page loading process
  • Performance optimization
  • security

Page loading process

Quotes:

  1. The entire process from entering the URL to rendering the page

  2. Window.onload differs from DOMContentLoaded

The form of the loaded resource

  • The HTML code
  • Media files, such as pictures and videos
  • Javascript css

The process of loading resources

  • DNS resolution: Domain name -> IP address
  • The browser sends an HTTP request to the server based on the IP address
  • The server processes the HTTP request and returns it to the browser

The process of rendering a page

  • Generate a DOM Tree from HTML code
  • Generate CSSOM from CSS code
  • Combine DOM Tree and CSSOM to form Render Tree
  • Render the page according to the Render Tree
  • encounter<script>Pause rendering, load and execute js code first, and continue when finished

Window. The onload and DOMContentLoaded

window.addEventListener('load'.function () {
    // The page will not be executed until all resources are loaded, including images and videos
})

document.addEventListener('DOMContentLoaded'.function () {
    // When the DOM is rendered, the image and video may not have finished loading
})
Copy the code

Examples:

1. The entire process from entering the URL to rendering the page

  • Downloading resources: Each resource type, downloading process
  • Render pages: combine HTML, CSS, JavaScript, images, etc

2. Window. onload vs. DOMContentLoaded

  • Window. onload: the page is executed only after all resources, including images and videos, have been loaded
  • DOMContentLoaded: When the DOM is rendered, the image and video may not be loaded

Performance optimization

  • Is a comprehensive problem, there is no standard answer, as far as possible comprehensive requirements
  • Some details may be asked separately: handwriting anti-shake, throttling

Performance optimization principles

  • Use memory caching or other methods
  • Reduces CPU computation and network loading time
  • Performance optimization for all programming: space for time

Where to start

  • Make it load faster
    • Reduce resource volume: compress code
    • Reduce the number of requests: merge code, SSR server-side rendering, caching
    • Use a faster network: CDN
  • Make rendering faster
    • CSS goes in the head and JS goes at the bottom of the body
    • Start executing JS as early as possible with DOMContentLoaded trigger
    • Lazy loading (image lazy loading, slide up to load more)
    • Cache DOM queries
    • Frequent DOM operations, merged together to insert DOM structures
    • Throttle and throttle

Stabilization debounce

  • Raises the change event after listening for text changes in an input box
  • Using the keyup event directly triggers the change event frequently
  • Anti – shake: The change event is triggered only when the user enters the end or pause
const input1 = document.getElementById('input1')

// let timer = null
// input1.addEventListener('keyup', function () {
// if (timer) {
// clearTimeout(timer)
/ /}
// timer = setTimeout(() => {
// // Simulates the change event
// console.log(input1.value)

// // Empty timer
// timer = null
/ /}, 500)
// })

// encapsulate the "anti-shake" function
function debounce(fn, delay = 500) {
    // Timer is in the closure
    let timer = null

    return function () {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() = > {
            fn.apply(this.arguments)
            timer = null
        }, delay)
    }
}

input1.addEventListener('keyup', debounce(function (e) {
    console.log(e.target)
    console.log(input1.value)
}, 600))

Copy the code

Throttling throttle

  • When you drag an element, always reach the location where the element is being dragged
  • If you use drag events, they will be triggered frequently and will easily stall
  • Throttling: This is triggered every 100 milliseconds, no matter how fast you drag it
const div1 = document.getElementById('div1')

// let timer = null
// div1.addEventListener('drag', function (e) {
// if (timer) {
// return
/ /}
// timer = setTimeout(() => {
// console.log(e.offsetX, e.offsetY)

// timer = null
/ /}, 100)
// })

/ / throttling
function throttle(fn, delay = 100) {
    let timer = null

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

div1.addEventListener('drag', throttle(function (e) {
    console.log(e.offsetX, e.offsetY)
}))

div1.addEventListener('drag'.function(event) {})Copy the code

security

Q: What are the common attacks on the Web front-end?

  • XSS cross-site request attack

  • XSRF cross-site request forgery

XSS cross-site request attack

For example, post on a blog site with an embedded script. The script content is to get the cookie and send it to my server (server with cross domain). If someone sees my post, I can easily harvest their cookies.

XSS prevention: Replaces special characters such as < to < > < span style = “box-sizing: border-box! Important;

Open source library XSS

XSRF cross-site request forgery

Imagine a scenario: you are shopping, you see an item, the ID of the item is 100, the payment interface is xxx.com/pay?id=100, but there is any verification. I am the attacker. I have my eye on a product with ID 200. I sent you an email with a very attractive title, but hidden in the body of the email is . As soon as you checked the email, you helped me buy the product with ID 200.

XSRF prevention: Use the POST interface. Add authentication, such as password, SMS verification code, and fingerprint.

References:

Beginner JavaScript Interview

JavaScript prototype inheritance

Prototype inheritance

The design idea of Javascript inheritance mechanism

promise

List of common Git commands

Charles Mobile phone agent Settings