The time of this study is a small wave front end for some basic knowledge of the summary of the interview (it didn’t involve framework), is not very full, on the one hand, and share with everyone, have a wrong place please teach me a lot this new, convenient your review on the other hand, your summary notes is also a way to strengthen the impression, refueling oh! Small waves try to learn the front end

HTML based

1. How to understand HTML semantics

Why semantics

  1. Pages are not just for people to see, machines to see and crawlers to see

  2. If the layout is all div+ CSS, sometimes the page will not load for some reason, and all div pages will not be user friendly

The characteristics of

  1. It is easier to read and helps to build a clear structure (increasing the readability of the code)
  2. Make search engines easier to read (SEO convenience)

2. What are the semantic tags

The usual semantic tags before HTML5

h1~h6 p br ul ol li dl dt dd em strong table thead tobdy tfoot td th caption

Points to note:

  • b,font,uDo not use such pure style labels
  • strongIs used in bold to emphasize importanceb bBold for the sake of bold),emIs italic is to emphasize (noti iThat’s italics.)
  • eachinputThe description text corresponding to the label needs to be usedlabelThe label
  • Form field to usefieldsetWrap it and use itlegendExplain the purpose of the form

Html5 adds a common semantic tag

header footer nav aside section artice

3. Block-level and inline elements

Block-level elements:

Ul Li ol DL DD DT table H1-H6 form P display: block

Inline elements:

A span b img input button display: inline-block

Style transformation:

  • display:blockInline elements are converted to block-level elements
  • display:inlineBlock-level elements are converted to inline elements
  • display:inline-blockConvert to inline elements

4. How to optimize DOM

  • Pseudo-elements can be used, and shadow-implemented content should be minimized

  • DOM implementation, such as clear float, style implementation, etc. Load on demand to reduce unnecessary rendering;

  • Reasonable structure, semantic tags

  • Using document fragments

  • DOM cache

  • InnerHTML instead of the appendChild

  • Virtual DOM

CSS based

1. Width calculation of the box model

Standard box model:

Default box-sizing: content-box

OffsetWidth: includes width + border + padding (excludes margin)

Let’s take this example

#box {
	width : 20px;
	padding : 20px;
	margin : 20px;
	border : 2px solid #ccc;
}
Copy the code

OffsetWidth:

document.getElementById('box').offsetWidth 64

Calculation of elastic box

Box-sizing: border-box

The total width is set as much as possible.

The width of the content is then calculated by itself

#box {
	width : 80px;
	padding : 20px;
	margin : 20px;
	border : 2px solid #ccc;
	box-sizing : border-box;
}
Copy the code

OffsetWidth:

document.getElementById('box').offsetWidth 80

If the width of the padding + border is greater than width

In this case, offsetWidth is just padding + border

2. Marign vertical overlap problem

Margin overlap is when the adjacent boundaries of two or more boxes (which may be adjacent or nested) (without any non-empty content, padding, or border between them) overlap to form a single boundary

For example, there are the following questions:

Calculate the distance between the first and last rows

<style>
      p {
        font-size: 16px;
        margin-top: 20px;
        margin-bottom: 10px;
        line-height: 1;
      }
    </style>
  </head>
  <body>
    <p>The first line</p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p>At the end of the line</p>
  </body>
Copy the code

All the p’s in the middle are gone, because there’s no height

The distance between the last row and the first row is 20px

Because there will be overlap in the margin portrait

Calculation method:

  • All are positive, take the largest;

  • Not all of them are positive, so we take the absolute value of them, and then we subtract the maximum value of the positive value from the maximum value of the absolute value;

3. The margin negative

  • margin-top margin-leftNegative values, the element moves up and left
  • margin-rightIf the value is negative, the right element is moved to the left (” subsequent elements “are pulled in the specified direction), and the element itself remains unchanged
  • margin-bottomNegative values, the right element moves up (” subsequent elements “are pulled in the specified direction), and the element itself stays the same

4.BFC

Block Formatting Context: Block Formatting Context

The BFC is a completely separate space (a separate render area) so that the children of the space do not affect the layout outside

Landing the rules

  • BFCIt’s a block-level element, and the block-level elements are arranged vertically one after the other
  • BFCA separate container within the page. The tags in the container do not affect the external tags
  • The vertical distance is determined by margin and belongs to the sameBFCThe margins of two adjacent labels will overlap
  • To calculateBFCThe float element is also calculated when the height of

Common conditions for BFC formation

  • floatDon’t fornone
  • positionabsolute fixed
  • overflownotvisible
  • displayflex inline-block table-cellEtc.

Common scenarios to clear floating margin overlap

5. Float layouts

The wings and Grail are classic PC layouts

The width on both sides is written dead, and the width in the middle is adaptive

The common structure is as follows

<body>
    <div class="container">
      <div class="main"></div>
      <div class="left"></div>
      <div class="right"></div>
    </div>
</body>
Copy the code

Common style

Set width: 100% for main so that it always fills the window for an adaptive effect.

<style type="text/css">
    body {
        margin: 0;
        width: 700px;
        min-width: 550px;
    }
    .container {
        width: 100%;
        height: 30vh;
    }
    .container > div {
        height: 100%;
        float: left;
    }
    .main {
        width: 100%;
        background-color: aqua;
    }
    .left {
        width: 100px;
        background-color: red;
    }
    .right {
        width: 200px;
        background-color: green;
    }
</style>
Copy the code

The holy grail layout

Add the padding property to the parent of the three elements to clear the space

 .container {
        width: 100%;
        height: 30vh;
        padding-left: 100px;
        padding-right: 200px;
}
Copy the code

Left to the left of main, set margin-left: -100%. Since the percentage of margin is relative to the parent element, it takes a full line of width to compensate for the value of margin, so the left can go to the position of main.

And then I’m going to position right relative to the width of itself to the left

.left {
        position: relative;
        margin-left: -100%;
        right: 100px;
        width: 100px;
        background-color: red;
}
Copy the code

Margin-right: -200px; margin-right: -200px; , which overlaps main with the width of right, so right will float to the right of main.

.right {
        margin-right: -200px;
        width: 200px;
        background-color: green;
}
Copy the code

Double wing layout

The two-wing layout needs to be changed, because main is set to 100%, so you cannot directly set margin for main

style

<style type="text/css">
      body {
        margin: 0;
        width: 550px;
        min-width: 500px;
      }
      .container {
        width: 100%;
        height: 30vh;
      }
      .container > div {
        height: 100%;
        float: left;
      }
      .wrap {
        background-color: aqua;
        height: 100%;
        margin: 0 200px 0 100px;
      }
      .main {
        width: 100%;
      }
      .left {
        width: 100px;
        background-color: red;
      }
      .right {
        width: 200px;
        background-color: green;
      }
</style>
Copy the code

structure

<body>
    <div class="container">
      <div class="main">
        <div class="wrap"></div>
      </div>
      <div class="left"></div>
      <div class="right"></div>
    </div>
</body>
Copy the code

Create another content layer, put all the content to be displayed in the wrap, and set margin for the wrap

Left to the left of main, set margin-left: -100%. Since the percentage of margin is relative to the parent element, it takes a full line of width to compensate for the value of margin, so the left will go to the left of main.

Then set right to the right of main. Just set margin-left to negative right width. For example, margin-left: -200px; , which overlaps main with the width of right, so right will float to the right of main.

.left {
        margin-left: -100%;
        width: 100px;
        background-color: red;
      }
.right {
        margin-left: -200px;
        width: 200px;
        background-color: green;
      }
Copy the code

You can also do this with Flex

CSS styles

html.body {
    margin: 0;
    padding: 0;
}
.box {
    display: flex;
    /* Left, center and right */
    justify-content: space-between;
    height: 100px;
}
.center {
    /* Fill the remaining area */
    flex: 1;
    height: 100px;
    background-color: red;
}
.left..right {
    /* Reduce the size of the space occupied by the scale of amplification */
    flex: 0 0 200px;
    height: 100px;
    background-color: skyblue;
}
Copy the code

HTML structure

<body>
    <div class="box">
        <div class="left"></div>
        <div class="center"></div>
        <div class="right"></div>
    </div>
</body>
Copy the code

Use positioning

The most commonly used is positioning

CSS styles

html.body {
    margin: 0;
    padding: 0;
}
.box {
	height: 100px;
}
.center {
    margin: 0 200px;
    height: 100px;
    background-color: red;
}
.left..right {
    position: absolute;
    top: 0;
    width: 200px;
    height: 100px;
    background-color: skyblue;
}
.left {
	left: 0;
}
.right {
	right: 0;
}
Copy the code

The structure is the same as above

<body>
    <div class="box">
        <div class="left"></div>
        <div class="center"></div>
        <div class="right"></div>
    </div>
</body>
Copy the code

6. Handwritten clearfix

General words sometimes require about 10s handwriting clearfix, write the best skilled do not hesitate

.clearfix:after {
    content : ' ';
    display : table;
    clear : both;
}
/* Compatible with IE low version */
.clearfix {
    *zoom : 1;
}
Copy the code

Flex implements a three-point dice

Flex basic syntax

Introduce a few common ones

The flex-direction attribute determines the direction of the spindle (that is, the alignment of the items).

  • rowIt is arranged from left to right
  • row-reverseIt’s arranged from right to left
  • columnIt’s arranged from the top down
  • column-reverseIt’s arranged from the bottom up

Flex-wrap allows you to wrap Flex projects in a newline arrangement.

  • nowrap(Default) : All Flex projects are arranged in a single line
  • wrap: All Flex projects are arranged in multiple lines, from top to bottom
  • wrap-reverse: All Flex projects are arranged in multiple lines, from bottom to top

The flex-flow property is shorthand for the Flex-direction and flex-wrap properties, and defaults to Row nowrap

The inter-content attribute defines how items are aligned on the spindle and how extra space is allocated.

  • flex-start(Default) : the sequence starts from the starting line
  • flex-end: Sequence relative to the finish line
  • center: Arranged in the center
  • space-between: Items are evenly distributed, with the first item at the start line and the last item at the finish line
  • space-around: The items are evenly distributed. There is the same white space on both sides of each item. The distance between adjacent items is the sum of the white space between the two items
  • space-evenly: Items are evenly distributed with equal distances between all items and between items and borders

The align-items property defines how items are aligned on cross axes.

  • stretch(Default) : Stretched display in the direction of cross axis
  • flex-start: Items are aligned according to the starting line of the cross axis
  • flex-end: Items are aligned according to the cross axis finish line
  • center: Align items in the middle of the intersecting axis
  • baseline: Align the cross axis according to the baseline of the first line

The align-content attribute defines alignment and allocation of extra space along the cross axis, similar to the effect of inter-content on the main axis.

  • stretch(Default) : Stretch display
  • flex-start: In order from the starting line
  • flex-end: Sequence relative to the finish line
  • center: Arranged in the center
  • space-between: Items are evenly distributed, with the first item at the start line and the last item at the finish line
  • space-around: The items are evenly distributed. There is the same white space on both sides of each item. The distance between adjacent items is the white space between the two items

To implement a three-point color (easy)

The idea is to use flex layouts. The main axis is space-between.

The second point intersecting the axis is center aligned. The third point items are aligned with the cross axis finish line.

structure

<div class="box">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
</div>
Copy the code

style

<style type="text/css">
      .box {
        width: 200px;
        height: 200px;
        border: 2px solid #ccc;
        border-radius: 10px;
        padding: 20px;

        display: flex;
        justify-content: space-between;
      }
      .item {
        display: block;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: rgb(210.225.228);
      }
      .item:nth-child(2) {
        align-self: center;
      }
      .item:nth-child(3) {
        align-self: flex-end;
      }
</style>
Copy the code

Positioning 8.

Absolute relative fixed

  • staticThe default position value, with no special positioning, follows the standard document flow
  • relativeIt is positioned relative to itself, but still occupies the original space and can be passedz-indexDefine the cascading relationship.
  • absoluteIf no ancestor element sets the location relative to the element’s nearest located ancestor element, then the reference isbodyLayer. Does not occupy the original space, at the same time can passz-indexDefine the cascading relationship.
  • fixedIt is fixed relative to the browser window and can pass throughz-indexDefine the cascading relationship. If his ancestral elements hadtransformThis property, it’s going to refer to it for fixed positioning

9. Center alignment

Horizontal center

  • inlineChemical element:text-align : center
  • blockChemical element:margin : auto
  • absoluteChemical element:left : 50% + margin-left Minus half of itself

Vertical center

  • inlineChemical element:line-heigthIs equal to theheight
  • absoluteChemical element:top : 50% + margin-topMinus one half of itselftransform (-50%,-50%)
  • absoluteChemical element:top, buttom, left, right = 0 + margin : auto

Flex parent box Settings

display: flex;
justify-content: center;
align-items: center;
Copy the code

Table-cell this is used to center elements that are not boxes, but can display:inline-block inside boxes

.father{
 display: table-cell;
 vertical-align: middle;
 text-align: center;
 /* The requirement is that the fixed width and height cannot be a percentage */
}
.son{
    display: inline-block
}
Copy the code

10. The line – the height of inheritance

  • Write a specific value, such as 30px, and inherit that value (easier to understand)
  • Write the ratio, such as 2/1.5, inherit the ratio (easier to understand)
  • Write a percentage, such as 200%, and inherit the calculated value (test point)

So let’s say we have a problem where we want to figure out the row height of P

<style type="text/css">
      body {
        font-size: 16px;
        line-height: 200%;
      }
      p {
        font-size: 18;
      }
</style>
Copy the code

structure

<body>
   <p>A</p>
</body>
Copy the code

If it’s a percentage, he’ll multiply it and inherit 16 times 200%

If it’s a number. Direct inheritance, with its own fontsize* number

11. Rem is what

Rem is a unit of length

  • Px, absolute unit of length, most commonly used
  • Em, a unit of relative length, relative to the parent element, not commonly used
  • Rem, a unit of relative length relative to the root element, is often used in responsive layouts

12. Common solutions for responsive layouts

  • Media-query: sets the root element font size according to different screen widths
  • Rem, based on the relative units of the root elements

13. Disadvantages of REM: “ladder” sex

In the following media query, for example, between 375 and 413, when the width of the screen reaches 376,378font size or 100px, it does not change in real time

Unless it goes beyond that

@media only screen and (max-width: 374px) {/* iphone5, size */ HTML {font-size: 16px; 86px; }} @media only screen and (min-width: 375px) and (max-width: 413px) {/* iphone6/7/8 and iPhone X */ HTML {font-size: 10.5pt; 100px; } } @media only screen and (min-width: < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px; }}Copy the code

14. Web viewport size

Web viewport size

  • window.screen.height// Screen height
  • window.innerHeight// Web viewport height
  • document.body.clientHeight/ / body height

vw/vh

  • vh1/100 of the viewport height
  • vw1/100 of the width of a web viewport
  • vmaxTake the maximum of both;vminTake the minimum of both

15. Redraw and backflow

Redraw: when the page is not out of the elements in the document flow, and simply for style change, change color, background, etc, for example, a browser style redraw back: refers to in the document flow, the size of the DOM, location, or certain properties change, causes the browser to dye share some or all of the documents

In contrast, reflux is more expensive than drawing. In addition, backflow can be caused by reading properties, such as reading the height and width of a DOM, or using the getComputedStyle method.

JS based

Basic knowledge of JS, specified syntax (ECMA262 standard)

JSWebAPI, web operation API(W3C standard)

The former is the basis of the latter, and the combination of the two can be truly practical

1. The class and inheritance

Briefly review the class constructor property. Note: Class is ES6 syntax

class Student {
    constructor(name, age) {
        this.name = name
        this.number = number
    }
    skill() {
        console.log(I was `The ${this.name}This year,The ${this.age}I will learn.)}}var zhangsan = new Student('Joe'.18)
console.log(zhangsan.name) / / zhang SAN
console.log(zhangsan.number) / / 18
zhangsan.skill() // MY name is Zhang SAN. I will study at 18 this year
Copy the code

Extends or overrides methods by inheriting extends Super

class People {
    constructor(name) {
        this.name = name
    }
    eat() {
        console.log(`The ${this.name}Can eat `)}}class Student extends People {
    constructor(name, number) {
        super(name)
        this.name = name + '[Outlaw fanatics]'
        this.number = number
    }
    skill() {
        console.log(I was `The ${this.name}This year,The ${this.age}I will learn.)}}var zhangsan = new Student('Joe'.18)
console.log(zhangsan.name) // Zhang SAN [A fanatic outside the Law]
console.log(zhangsan.number) / / 18
zhangsan.skill() // MY name is Zhang SAN. I will study on the 18th of this year
zhangsan.eat() // Zhang SAN [A fanatic outside the Law] can eat very well
Copy the code

typeof Student “function” typeof People “function”

Class is also a function

2. Variable type

The original type

Note: The primitive type does not contain Object.

ECMAScript defines six primitive types:

  • Boolean
  • String
  • Number
  • Null
  • Undefined
  • Symbol (ES6 New Definition)

typeof

Typeof can determine the following types:

  • undefined
  • boolean
  • number
  • string
  • object
  • function
  • symbol

Note:

Typeof null results in object, which is actually a bug in Typeof. Null is the original value, non-reference type

The result of a typeof array is object. There is no array in the result. All the reference types except function are object

Typeof Symbol(typeof Symbol()

Type determination – instanceof

Instanceof is based on the prototype chain lookup

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

3. The prototype

The prototype

A stereotype is an object, and the instance “inherits” the properties of that object. A property defined on the stereotype is inherited by the instance. The “inherit” behavior is implemented inside the new operator.

The constructor has a property called prototype inside it that gives you access to the prototype

Implicit archetypes show archetypes

Student is the constructor, and student. prototype is the prototype

The instance accesses the prototype through __proto__

So the two are equivalent:

  • zhangsan.prototypeExplicit prototype
  • zhangsan.__proto__Implicit stereotype
  • zhangsan.prototype= = =zhangsan.__proto__

4. The prototype chain

Prototype chain

Stereotypes also have a __proto__ attribute that allows them to access their own stereotypes

Take a chestnut

When an instance of Student, zhangsan, calls a property or method that doesn’t have the property itself, it accesses the stereotype through __proto__ to see if it has the property or method, and if it does, it can use it directly. If not, look for the __proto__ of the stereotype and continue looking for the attribute or method until the top level is null. If not, it does not exist

This chain of upward searches is what we call a prototype chain

5. How to accurately determine whether a variable is an array

Obviously typeof [] does not give you the desired result “object”

The common method is instanceof based on prototype chain lookup

And through the Object. The prototype. ToString

  • [] instanceof ArrayResults:true
  • Object.prototype.toString.call([])Results:"[object Array]"

6. Simple, hand-written jQuery with plugins and extensibility in mind

I’m going to write some simple HTML to use later

<ul>
    <li>Am I</li>
    <li>Am I</li>
    <li>Am I</li>
    <li>Am I</li>
    <li>Am I</li>
</ul>
Copy the code

So let’s just write a simple jQuery

class jQuery {
    // Get the element to save
    constructor(selector) {
        const result = document.querySelectorAll(selector)
        const lenght = result.length
        for (let i = 0; i < result.length; i++) {
            this[i] = result[i]
        }
        this.lenght = lenght
        this.selector = result
    }
    // Implement the get method to turn jQ into Dom
    get(index) {
        return this[index]
    }
    / / traverse
    each(fn) {
        for (let i = 0; i < this.lenght; i++) {
            const ele = this[i]
            fn(ele)
        }
    }
    // Bind the event
    on(type, fn) {
        this.each((ele) = > {
            ele.addEventListener(type, fn, false)})return this}}// Add a plug-in
jQuery.prototype.dialog = function () {
    alert('This is a dialog')
    return this
}
$$$$$$$
const$=(selector) = > new jQuery(selector)
/ / use
$('ul li').on('click'.function () {
    console.log(this)})// Call the added method
$().dialog()
Copy the code

You can keep building wheels

/ / build the wheels
class myJQuery extends jQuery {
    constructor(selector) {
        super(selector)
    }
    // Extend your method here
    css(json) {
        for (let key in json) {
            this.each((ele) = > {
                ele.style[key] = json[key]
            })
        }
        return this}}/ / use
new myJQuery('ul li').css({
    background: 'red',})Copy the code

7. Scope and closure

In simple terms, scope refers to the area of a program where variables are defined, which determines access to them by the currently executing code.

Due to scope limitation, each independent execution code block can only access variables in its own scope and the outer scope, and cannot access variables in the inner scope.

In javascript, for the most part, there are only two scope types:

  • Global scope: The global scope is the outermost scope of a program and always exists.
  • Function scope: A function scope is created only when the function is defined and is contained within the parent function scope/global scope.

Free variables

  • A variable is not defined in the current scope, but is used
  • Go to the upper scope, layer by layer, until you find it
  • Error Xx is not defined if the global scope is not found

The scope chain

If the free variable in use is not defined in the current scope, it is searched in the outer scope. If it is not, it is searched in the outer scope. If it is not in the global scope, it is not reported in the ReferenceError

Block-level scope

The ES6 standard proposes the use of let and const instead of var keywords to “create block-level scope.”

Simply put, within curly braces {… } is the block-level scoped region.

{
  let a = 1;
}

console.log(a); // ReferenceError
Copy the code

One common use case for scope is modularity. Global scope pollution and variable name conflict, bloated code structure and low reusability.

Closures: Functions that have access to variables inside other functions are called closures.

Is a special case of scoped applications

There are two manifestations: a function is passed as an argument and a function is returned as a return value

Application scenarios: Most scenarios require the maintenance of internal variables.

Example a

function test() {
    const a = 30
    return function print() {
        console.log(a)
    }
}
const a = 100
test()() / / 30
Copy the code

Example 2

const b = 30
function fun() {
    console.log(b)
}
function test2(fn) {
    const b = 100
    fn()
}
test2(fun) / / 30
Copy the code

All search for free variables is in the function definition, to the upper scope is not in the execution of the place!

A situation where the memory footprint cannot be freed due to overuse of closures is called a memory leak.

8.this

What value does this take when the function is executed rather than when it is defined

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

fn1.call({ a: 1 }) //{ a: 1 }
fn1.bind({ b: 2}) ()//{ b: 2 }
Copy the code
  1. In normal functions: this->window
  2. Timer: this->window
  3. Constructor: this-> The currently instantiated object
  4. Event handler: this-> event triggers object
  5. The common understanding in JS is that whoever calls this refers to the person

9. Create 10 A labels, and the corresponding serial number will pop up when clicking

Look at block-level scope

for (let i = 0; i < 10; i++) {
    const a = document.createElement('a')
    a.innerHTML = i + '<br>'
    a.addEventListener('click'.function (e) {
        e.preventDefault()
        alert(i)
    })
    document.body.appendChild(a)
}
Copy the code

10. Application of closures in actual development

Hiding data only provides the API to ensure data security

function createCache() {
    const data = {}
    return {
        set(key, val) {
            console.log(data, key, val)
            data[key] = val
        },
        get(key) {
            return data[key]
        },
    }
}
const c = createCache()
c.set('a'.'haha ')
console.log(c.get('a')) //haha
Copy the code

11. Write the call,apply, and bind functions

Hand-written call,apply,bind compare basic

Handwritten call, call performance is higher than apply

Function.prototype.call1 = function (obj, ... args) {
  // Save the passed this
  const context = obj
  // Avoid overwriting the original method, so use Symbol to ensure uniqueness
  const fn = Symbol(a)// Add the method to the passed this, and then the method points to the caller of call1
  context[fn] = this
  // Execution method
  constresult = context[fn](... args)// Remove the fn method passed to this
  delete context[fn]
  // Return the result
  return result
}

// Use the method
function sum(num1, num2) {
  console.log(this.base + num1 + num2)
}

let obj = {
  base: 1,
}

sum.call1(obj, 100.200) / / 301

Copy the code

Handwritten apply

// The second argument is not expanded
Function.prototype.apply1 = function (obj, args) {
  // Save the passed this
  const context = obj
  // Avoid overwriting the original method, so use Symbol to ensure uniqueness
  const fn = Symbol(a)// Add the method to the passed this, and then the method points to the caller of call1
  context[fn] = this
  // Execution method
  constresult = context[fn](... args)// Remove the fn method passed to this
  delete context[fn]
  // Return the result
  return result
}

// Use the method
function sum(num1, num2) {
  console.log(this.base + num1 + num2)
}

let obj = {
  base: 1,
}

sum.apply1(obj, [100.200]) / / 301
Copy the code

Write a bind

Function.prototype.mybind = function () {
    // Convert arguments to array equivalent const args = arguments.slice()
    const args = Array.prototype.slice.call(arguments)
    // Take the pass this out
    const myThis = args.shift()
    // Save this for the current function
    const self = this
    // Return a function
    return function () {
        // Execute the function and return the result
        return self.apply(myThis, args)
    }
}

function fn(a, b) {
    console.log(this, a + b)
}
fn.mybind({ a: 1 }, 1.2) ()//{a: 1} 3
Copy the code

Hand-written complete bind supports new

Function.prototype.bind = function(OThis, ... outherArgs) {
	// Cache the called function
    const thatFunc = this
    const fBind = function(. innerArgs) {
        // Check whether the function is new or executes directly
        return thisFunc.apply(
        	this instanceof thatFunc ? this : OThis, [...outherArgs, ...innerArgs]
        )
    }
    // Do not contaminate thatFunc prototype
    fBind.prototeye = Object.create(thatFunc.prototype)
    // Return a function
    return fBind
}
Copy the code

sample

function fn1() {
  console.log('fn1')}function fn2() {
  console.log('fn2')
}

fn1.call.call(fn2) // 'fn2'
// Call is called for the first time
// context = fn2 ; this = fn1
//return fn2[fn1]() ---> fn2.fn1()
// The second call
// context = fn2 ; this = call
//return fn2[call](window) ---> window.fn2() ---> 'fn2'
fn1.call.call.call.call.call.call.call.call(fn2) // 'fn2'
Copy the code

12. The asynchronous

JS is a single threaded language that can only do one thing at a time

Browsers and NodeJS already support JS startup processes such as Web workers

JS and DOM render share the same thread, because JS can modify the DOM structure

Because it’s single threaded

Wait (network request, scheduled task) can not be stuck, need to asynchronous, using the callback function form

Synchronous and Asynchronous

  • JS based is a single threaded language
  • Asynchrony does not block code execution
  • Synchronization blocks code execution
/ / asynchronous
console.log(100)
setTimeout(function() {
    console.log(300)})console.log(200)
// Does not block code
Copy the code
/ / synchronize
console.log(100)
alert(1)// Execution is stuck here
console.log(200)
Copy the code

Application scenario:

Network requests, such as Ajax image loads

Scheduled tasks, such as setTimeout

Callback hell

For example, in this case, all the way down (functions are nested as arguments)

The main thing about callback hell is that there are too many layers of nested functional logic code, which makes it difficult to read and maintain. The most important aspect of avoiding callback hell is to remove the functionality and keep the code simple

// Collect the first data
$.get(url1, (data1) = > {
    console. log(datal)
    // Get the second data$.get(url2, (data2)) => {console. Log(data2)
        // Obtain the third data
        $.get(url3, (data3) = > {
            console. log(data3)
            // It is possible to obtain more data})})})Copy the code

14.Promise

Promise: is a way to write asynchronous code that still executes in a top-down manner and handles more types of errors by encouraging try/catch style error handling

Promise solves the problem of callback hell nesting

1. A simple example of Promise

function getData(url) {
    return new Promise((resolve, reject) = > {
        $.ajax({
            url,
            success(data) {
                resolve(data)
            },
            error(err) {
                reject(err)
            },
        })
    })
}
const url1 = '/data1.json'
const ur12 = '/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

2. Load an image with a Promise by hand

function loadImg(url) {
    return new Promise((resolve, reject) = > {
        const img = document.createElement('img')
        img.onload = function () {
            resolve({ img, msg: 'Image loaded successfully' })
        }
        img.onerror = function () {
            reject(new Error(`${img.src}Image loading failed))
        }
        img.src = url
    })
}
loadImg('./img/2.jpg')
.then((res) = > {
    console.log(res)
    document.body.appendChild(res.img)
})
.catch((res) = > {
    console.log(res)
})
Copy the code

15. Event loop

The relationship between asynchrony and event loops

  • JS is single-threaded
  • Asynchrony is based on callbacks
  • Event loop is the implementation principle of asynchronous callback

How is the JS code executed

  • Front to back, line by line
  • If an error occurs on one line of execution, the following code is stopped
  • The synchronous code is executed before the asynchronous code is executed
console.log('Hi')
setTimeout(function cb1() {
    console.Log('cb1') / / cb callback
}, 5000)
console.log('Bye')
// The print order is Hi Bye cb1
Copy the code

Event loop procedure (macro/microtask not covered yet)

  1. Sync the code line by lineCall StackExecute (the synchronization task is executed by pressing the stack on the stack)
  2. In case of asynchrony, it will first “record” and wait for the timing (timing, network request, etc.)
  3. When the time is right, move toCallback Queue(Callback queue)
  4. Such asCall StackEmpty (that is, the synchronized code has finished executing)Event LoopStart to work
  5. Wheel office to findCallback Queue(callback queue), if any, move toCall Stackperform
  6. And then continue to search for (perpetual motion machine)

Draw your own picture, wrong place please give more advice

16. Promise

Three states

  • pendingNo then or catch is triggered
  • resolvedThe subsequent THEN callback is fired
  • rejectedSubsequent catch callbacks are fired

A manifestation or change of state (the change is irreversible)

Pending a > resolved or pending a > rejected

Effects of Then and Catch on states (important)

  • thenReturn to normalresolved, if there is an error, returnrejected
  • catchReturn to normalresolved, if there is an error, returnrejected

Chained calls to then and catch

There are a lot of online promise problems, so HERE’s a simple, printed version

const p1 = Promise.resolve().then(() = > {
  return 100
})
// No error occurred in P1.THEN and the return to Resolved triggers a subsequent THEN callback
p1.then((data) = > {
  console.log(data) / / 100
}).catch(() = > {
  console.error(new Error('err')) // This line of code must not be executed
})

// Rejected executes the catch callback later
const p2 = Promise.reject().then(() = > {
  throw new Error('then error') // This line of code must not be executed
})

p2.then(() = > {
  console.log('200') // This is not implemented either
})
.catch(() = > {
  console.log('300')
  throw new Error('err') // Return rejected and execute catch
})
.then(() = > {
  console.log('400')// This is not implemented either
})
.catch(() = > {
  console.log('500') // Return to Resolved and execute the following
})
.then(() = > {
  console.log('600')})Copy the code

The final print is 100, 300, 500, 600

Two simple ones

Example 1

Promise.resolve()
  .then(() = > {
    console.log(1)
    throw new Error('erro1')
  })
  .catch(() = > {
    console.log(2)
  })
  .then(() = > {
    console.log(3)})Copy the code

I printed 1, 2, 3

Example 2

Promise.resolve()
  .then(() = > {
    console.log(1) / / 1
    throw new Error('erro1')
  })
  .catch(() = > {
    console.log(2) 
  })
  .catch(() = > {
    console.log(3)})Copy the code

I printed 1, 2

There are many examples on the Internet, so you can practice more sometimes

17.async / await

Async/await and callback hell

  • Promise then catchChained calls, but also based on callbacks
  • async/ awaitIs synchronous syntax,eradicationThe ultimate weapon of asynchronous callbacks
  • But andPromiseThey are not mutually exclusive; rather, they complement each other

Async/await relationship with Promise

  • performasyncFunction, which returns 0Promiseobject
  • awaitThe equivalent ofPromisethethen
  • try... catchCan catch exceptions, instead ofPromisecatch

Here are some examples

! (async function () {
  const p1 = Promise.resolve(300)
  const data = await p1 // await is equivalent to Promise then
  console.log('data', data) })() ! (async function () {
  const datal = await 400 //await is equivalent to promise.resolve (400)
  console.log('datal', datal)
})()

function fn1() {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve(500)},1000)})}! (async function () {
  const data2 = await fn1()
  console.log('data2', data2) })() ! (async function () {
  const p4 = Promise.reject('err') / / rejected state
  try {
    const res = await p4
    console.log(res)
  } catch (ex) {
    console.error(ex) // try.. Catch = promise catch
  }
})()
Copy the code

Nature of asynchrony

  • async/ awaitIs the ultimate weapon to eliminate asynchronous callbacks
  • JS is still single threaded, it has to be asynchronous, it has to be based onevent loop
  • async/awaitIt’s just a grammatical candy, but it tastes good!

Do two examples using the event loop

Sample a

async function async1() {
  console.log('async1 start')
  await async2()
  // Await code is treated as an asynchronous callback
  console.log('async1 end')}async function async2() {
  console.log('async2')}console.log('script start')
async1()
console.log('script end')
Copy the code

The resulting print is:

script start

async1 start

async2

script end

async1 end

Example 2

! (async function () {
  async function async1() {
    console.log('async1 start') / / 2
    await async2()

    console.log('async1 end') / / 4
    await async3()
    console.log('async1 end 2') / / 6
  }

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

  async function async3() {
    console.log('async3') / / 5
  }
  console.log('script start') / / 1
  await async1()
  console.log('script end') / / 7}) ()Copy the code

The printout results are as follows:

18.for … of

for .. In (and forEach for) are regular synchronous traversals

for .. Of is often used for asynchronous traversal

Here’s an example to illustrate the difference

function test(item) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve(item * item)
    }, 1000)})}const arr = [100.200.300]

arr.forEach(async (i) => {
  console.log(await test(i))
})
Copy the code

The example above uses synchronous traversal to print out all the results after 1000ms, rather than every second

Use for… Of traversal

function test(item) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve(item * item)
    }, 1000)})}const arr = [100.200.300]

!(async function () {
  for (let item of arr) {
    console.log(await test(item))
  }
})()
Copy the code

Use for… The of traversal is printed at 1000ms

19. Macro/microtask

Brief introduction:

Microtasks and macro tasks are asynchronous tasks and belong to the same queue. The main difference is the order in which they are executed

  • Macro tasks: setTimeout, setInterval, Ajax, DOM events
  • Microtasks: Promise async/await
  • Microtasks are executed earlier than macro tasks

So let’s do a simple demo

console.log(1)
setTimeout(() = > {
  console.log(2)},1)
Promise.resolve().then(() = > {
  console.log(3)})console.log(4)
Copy the code

Results: 1, 4, 3, 2

Let’s talk about DOM rendering

  • JS is single-threaded and shares a thread with DOM rendering
  • When javascript executes, you need to leave some time for DOM rendering
  • Synchronization tasks are completed when the Call Stack is cleared (that is, when polling ends)
  • Both are opportunities to rerender the DOM, and to rerender if the DOM structure changes
  • And then it triggers the next Event Loop.

Macro task: Triggered after DOM rendering, such as setTimeout

Microtasks: Triggers before DOM rendering, such as Promise

Microtasks are defined by ES6 syntax

Macro tasks are specified by the browser

Macrotask/microtask relationships in the event loop

Let me do two examples

Sample a

async function async1() {
  console.log('async1 start')
  await async2()
  // Await as an asynchronous callback. Here is the microtask
  console.log('async1 end')}async function async2() {
  console.log('async2')}console.log('script start')

/ / macro task
setTimeout(() = > {
  console.log('setitmeout')},0)

async1()

Copy the code

Results:

Example 2

new Promise((resolve) = > {
  console.log('promise1')// When a Promise is initialized, it executes immediately
  resolve()
}).then(() = > { 
  console.log('promise2')Micro / / task
})
console.log('script end')
Copy the code

Results:

20. DOM node

DOM is a tree structure (DOM tree)

Node operation is simple to take a few examples, the basic API does not need much introduction

const div1 = document.getElementById('diV1')/elementsconst divList = document.getElementsByTagName('div') / / collection
console.log(divList.length)
console.log(divList[0])
const containerListe = document.getElementsByClassName('container') / / collection
const pList = document.querySelectorAlL('p') / / collection

Copy the code

Property of the DOM node

const pListe = document.querySelectorAll(p)
const p = pList[0]
console.log(pList[0].style.width)/get the style p.style.width ='100px' // Modify the style
console.log(p.className) / / for the class
p.className = 'p1' / / modify the class
// Get nodeName and nodeType
console.log(p.nodeName)
console.log(p.nodeType)
Copy the code

Attribute of the DOM node

const pListe = document.querySelectorAll(p)
const p = pList[0]
p.setAttribute('data-src'.'./21.pro.jpg')
console.log(p.getAttribute('data-src'))

p.setAttribute('style'.'color:#ccc; ')
console.log(p.getAttribute('style'))
p.removeAttribute("style");
Copy the code

Property: Modifies object properties that are not reflected in the HTML structure

Attribute: Modifying an HTML attribute changes the HTML structure

Both have the potential to cause DOM rerendering

21.DOM node operations

Node operation

const p = document.createElement("p"); // Create the DOM element
p.remove(); / / delete p
p.removeChild(clildEle) // Remove the child elements from p
const p2 = p.cloneNode(true)/ / clone
box.appendChild(p);// Append to the end
box.appendChild(p2);// If p2 is already in the DOM, adding it to the box is a mobile node
p.insertBefore(newele,ele) // Insert newele before ele element in p element
box.replaceChild(newEle,oldEle) / / replace the dom
console.log(p.nodeType); // Determine the type of p
Copy the code

Connections between nodes

  • ParentNode searches for the parentNode

  • ChildElementCount returns the number of child elements excluding text nodes and comments

  • FirstChild finds the first byte point of the specified node

  • LastChild finds the last byte point of the specified node

  • PreviousSibling finds the last node of the specified node

  • FirstElementChild returns the first child

  • LastElementChild returns the last child element

  • PreviousElementSibling Returns the previous adjacent sibling element

  • NextElementSibling Returns the next adjacent sibling element

  • NextSibling finds the next node of the specified node

22. The DOM performance

  • DOM operations are “expensive”; avoid frequent DOM operations
  • Cache DOM queries
  • Change frequent operations to one-time operations

DOM queries are cached

// Do not cache the query
for (let i = 0; i < document.getElementsByTagName('p').length; i++) {
  // Query each loop
}

// Cache the DOM query
const pList = document.getElementsByTagName('p')
const length = pList.length
for (let i = 0; i < length; i++) {
  // Query once after cache
}
Copy the code

Change frequent operations to one-time operations

// Create a document shard
const fragment = document.createDocumentFragment()

// Insert content
for (let i = 0; i < 10; i++) {
  const img = document.createElement('img')
  img.src = './img/2.jpg'
  fragment.appendChild(img)
}

// When done, insert the document fragment directly into the DOM
document.body.appendChild(fragment)
Copy the code

23. Go over the BOM simply

The core object of the BOM window:

  • windowIs a global object
  • Browser windowJavaScriptinterface

navigator

The client identifies the browser standard, which is used to record and detect the main information about the browser and the device

How to identify the browser?

const ua = window.navigator.userAgent
const isChrome = ua.indexOf('Chrome')
console.log(isChrome)
Copy the code

screen

Objects that hold client-side capabilities are a few common properties

  • height: Screen pixel height
  • left: The distance in pixels to the left of the current screen
  • top: The distance in pixels from the top of the current screen
  • width: Screen pixel width

Location can be used to disassemble the URL

  • protocolAgreement:
  • host: Domain name and port
  • hostname: Server name
  • pathname:urlThe path
  • hash: hash value
  • href:urlfield
  • search: Query field

history

  • go(): Jump page
  • forwardAdvance:
  • back()Back:

24. The event

Just a brief introduction to event binding, which I believe everyone knows

let btn = docment.getElementById('btn')
// Bind with on
btn.onclick = funcition(){
    // Event handling
}

/ / use the addEventListener
btn.addEventListener('click'.function(){
    // Event processing logic
},false)
Copy the code

Describe the flow of the event bubble

  • Based on the DOM tree structure
  • Events bubble along the triggering element web
  • Application scenario: Event agent

Benefits of event proxies

  • The code is simple
  • Reduce browser memory usage
  • But don’t abuse it
  • For those newly added elements, it is best to use the event broker

Example: Infinite drop-down list of images, how to listen for each image click

  • The event agent
  • Get the trigger element with E.t. get
  • Matches is used to determine if it is a trigger

Encapsulate your own generic event binding functions

Object.prototype.bindEvent = function (type, selector, fn) {
  // If the third parameter is null, it is not an event proxy
  if (fn == null) {
    fn = selector
    selector = null
  }
  this.addEventListener(type, (e) = > {
    // Save the triggering element of the event
    const target = e.target
    // Event proxy
    if (selector) {
      if (target.matches(selector)) {
        fn.call(target, e)
      }
    } else {
      // Common event binding
      fn.call(target, e)
    }
  })
}

const ul = document.querySelector('ul')

// Common use
ul.bindEvent('click'.function () {
  console.log(this)})// Event proxy
ul.bindEvent('click'.'li'.function () {
  console.log(this)})Copy the code

25.ajax

Write a simple Ajax

A get request

const xhr = new XMLHttpRequest()
/ / get request
xhr.open('GET'.'./test.json'.true)
xhr.onreadystatechange = function () {
  if (xhr.status === 200 && xhr.readyState === 4) {
    console.log(xhr.responseText)
  }
}

xhr.send(null)
Copy the code

A post request

const xhr = new XMLHttpRequest()
/ / post request
xhr.open('POST'.'localhost://mytest'.true)
xhr.onreadystatechange = function () {
  if (xhr.status === 200 && xhr.readyState == 4) {
    console.log(xhr.responseText)
  }
}
xhr.send(
  JSON.stringify({
    name: 'zhangsan'.age: 18,}))Copy the code

Status code XHR. ReadyState

  • 0- (uninitialized) The send(method) has not been called
  • 1- (loaded) The send(method has been called and the request is being sent
  • 2- (load complete) The send() method is complete and has received all the response
  • 3- (Interaction) Parsing response content
  • 4- (Done) The response content is resolved and can be invoked on the client

The response code XHR. Status

  • 2xx – Indicates that the request was successfully processed, for example, 200
  • 3xx – Requires redirection, browser direct jump, such as 301 302 304
  • 4xx – A client request error, such as 404 403
  • 5xx – Server error

26. Cross domain

What’s cross-domain

Simply put: Browsers cannot execute scripts from other sites due to the same origin policy

All cross – domain, must pass server side permit and cooperate

Without the permission of the server to implement cross-domain, indicating that the browser has vulnerabilities, a red flag

The same-origin policy

  • When making an Ajax request, the browser requires that the current web page and server must be the same source (security)
  • Cognate: Must be the same as the protocol, domain name, and port
  • Front end: a.com:8080/; Server :b.com/api/xx (different sources)

Ignore the same origin policy when loading images, CSS, and JS

  • <img SRC = cross-domain image address />Can be used for statistics, can use the third party E statistical services
  • <link href= cross-domain CSS address />You can use a CDN, which is usually an outdomain
  • <script SRC = cross-domain JS address > </script>Can use CDN, can be implementedJSON

jsonp

Because script tags can send GET requests, such as referring to CDN, we can dynamically create script tags and then request a reference url to achieve cross-domain communication

  • The script tag can bypass cross-domain restrictions
  • The server can return any dynamic splicing of data
  • So,<script>You can get cross-domain data as long as the server is willing to return it

Write a simple example of JSONP

In the background is Node.js + Express

app.get('/info'.(req,res) = >{
    const result = 'fn({name : 'Zhang SAN'}) '
    // Return fn({name: 'three '}) and execute
    res.send(result) / /... 3
})
Copy the code

The front end

<script>
    // First define an fn function............ 1
    window.fn = function (data) {
    // Print the obtained data
    console.log(data) / /... 4
}
</script>
// Send jSONp request.............. with script tag 2
<script src="http://localhost:8080/mytest/info"></script>
Copy the code

Of course, you can also wrap a jSONP function yourself

function jsonp(options) {
  // Create script dynamically
  const script = document.createElement('script')
  // Concatenate string variables
  let params = ' '

  // Concatenate multiple parameters
  for (let attr in options.data) {
    params += '&' + attr + '=' + options.data[attr]
  }
  // Generate function names randomly
  const fnName = 'myJsonp' + Math.random().toString().replace('. '.' ')
  // Make fnName a global function
  window[fnName] = options.success
  // Add the SRC attribute to the script
  script.src = options.url + '? callback=' + fnName + params
  // add the script to the page
  document.body.appendChild(script)
  // Remove script after trigger
  script.onload = function () {
    document.body.removeChild(this)}}/ / use
btn.onclick = function () {
  jsonp({
    url: 'url'.success: function (data) {
      console.log(data)
    },
  })
}

Copy the code

JQuery implementation json

$.ajax({
  url: 'url'.// Must be specified as jSONp
  dataType: 'jsonp'.// The name of the custom callback function. The default value is in jqueryXXX format
  jsonpCallback: 'callback'.success: function (data) {
    console.log(data)
  },
})
Copy the code

By default, a JSONP request made with jQuery automatically takes a callback=jQueryxxx parameter. JQuery is a randomly generated callback function name.

CORS – The server sets the HTTP header

// Allow the client to send content-type and xx-custom Header headers to the server
// Note: Multiple request headers are separated by commas
res.setHeader('Access-Control-Allow-Headers'.'Content-Type, X-Custom-Header')
// Only POST, GET, DELETE, and HEAD request methods are allowed
res.setHeader('Access-Control-Allow-Methods'.'POST, GET, DELETE, HEAD')
// Allow all HTTP request methods
res.setHeader('Access-Control-Allow-Methods'.The '*')
Copy the code

27. Ajax tools

So much for $. Ajax wrapped in jQuery

Fetch: Simple example default GET request

fetch('url')
  .then(data= > console.log(data))
  .catch(err= > console.log(err)); 
Copy the code

Fetch is implemented with Promise. We can directly use async to optimize the above code to reduce callbacks and make it more semantic and easy to understand

! (async function(){
    try{
        const res = await fetch('url')
        console.log(res)
    }catch(err){
		console.log(err)       
    }
})() 
Copy the code

POST request of Fetch

fetch(url, {
    method: 'post'.headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: 'name="zhangsan"&age=18'
})
.then(function (data) {
    console.log(data);
})
.catch(function (err) {
    console.log(err);
});

Copy the code

The credentials need to be set when you wear cookies

fetch(url, {
  credentials: 'include'
})
Copy the code

The basic use of AXIos should go without saying. You use it every day

28. Storage

Description Cookie localStorage sessionStorage differences

cookie

  • Itself is used in browsers andservercommunication
  • inhtml5Previously “borrowed” to local storage
  • availabledocument.cookie =To modify the

Cookie shortcomings

  • The maximum storage size is 4KB
  • httpThe request needs to be sent to the server to increase the amount of data requested
  • Can only usedocument.cookie =To modify, too crude

LocalStorage and sessionStorage

  • HTML5Specially designed for storage, the maximum storage is 5M
  • The API is simple to usesetItem getItem
  • Not ashttpThe request is sent
  • localStorageData is stored permanently unless coded or manually deleted
  • sessionStorageData exists only in the current session and is cleared when the browser closes
  • In general uselocalStorageIt’ll be a little more

29.HTTP

Status code classification

  • 1XX The server receives the request
  • 2XX the request succeeds, for example, 200
  • 3xx redirection, for example, 302
  • 4XX client error, such as 404
  • 5XX The server is incorrect, for example, 500

Common status code

  • 200successful
  • 301Permanent redirection (withlocation, automatically handled by the browser)
  • 302Temporary redirection (withlocation, automatically handled by the browser)
  • 304The resource has not been modified
  • 404Resource not found
  • 403Have no legal power
  • 500Server error
  • 504Gateway timeout

About protocols and specifications

  • It’s a convention
  • Everyone is required to follow suit
  • Don’t violate the specification, such as Internet Explorer

http headers

Request Headers

  • Accept Indicates the data format that the browser can Accept
  • Accept-encoding Indicates the compression algorithm accepted by the browser, such as Gzip
  • Accept-languange Indicates a language that can be accepted by the browser, such as zh-cn
  • Connection: keep-alive – – The TCP Connection is used repeatedly
  • cookie
  • Host
  • User-agent (UA) Indicates the browser information
  • Content-type Specifies the format of the data to be sent, for example, Application/JSON

Response Headers

  • Content-type Specifies the format of the returned data, such as Application/JSON
  • Content-length Specifies the size of the returned data, in bytes
  • Content-encoding Compression algorithm of returned data, such as gzip
  • Set-Cookie

Customize headers

header : {
    'X-Requested-with': 'XMLHttpRequest'
}
Copy the code

30. HTTP cache

About the cache

  • Reduce bandwidth, reduce the number of requests, reduce server stress, and improve performance
  • Browser caching is generally for static resources such as JS, CSS, images, etc

Mandatory cache

If it expires, return cache-control

Cache-Control

Response Headers controls the logic that forces caching

For example, cache-control: max-age=31536000 (in seconds)

  • Public: Resources can be cached by both the client and the server.
  • Privite: Resources can be cached only by clients.
  • No-cache: The client caches resources. However, whether to cache resources is verified by the negotiated cache.
  • No-store: No cache is used.
  • Max-age: indicates the cache expiration date.

About Expires

  • amenResponse HeadersIn the
  • Also for controlling cache expiration
  • Has beenCache-ControlInstead of

Negotiate the cache

  • Server-side caching policy
  • The server determines whether the client resources are the same as the server resources
  • If so, return 304, otherwise return 200 and the latest resource

Resource identifier

  • inResponse HeadersThere are two
  • Last-ModifiedThe last modification time of the resource
  • EtagUnique identifier of the resource (- a string, similar to a human fingerprint)

Here is a Headers instance

Last-modified and Etag

  • Will be used preferentiallyEtag
  • Last-ModifiedCan only be accurate toSecond level
  • If the resource is repeatedly generated without changing the content, thenEtagTo be more accurate

Cache flow chart

The impact of three refresh operations on the cache

Normal operations: Enter the URL, forward link, forward or backward in the address bar

Manual refresh: F5, click refresh button, right click menu refresh

Force refresh: CTRL + F5

  • Normal operation: Force cache is valid, negotiate cache is valid
  • Manual refresh: The forced cache is invalid and the negotiated cache is valid
  • Forced refresh: Forced cache invalidation and negotiated cache invalidation

About the Development Environment

1.git

The most commonly used code versioning tool

Large projects require collaborative development, and you must be familiar with Git

If you don’t know or haven’t used Git before, you won’t pass the interview

  • The Mac OS comes with git. On Windows, you can download and install git from the official website
  • Git servers include Github, coding.net and so on
  • Large companies set up their own git Intranet services

I’m not going to go into a lot of detail here, but I’m just going to talk about the operations that we use a lot

The first time you use Git, configure the user information

  • User name:Git config --global user.name
  • Household email:Git config --global user.email ""

Initializing the warehouse

  • Create a new local repository:git init
  • Or copy the project from a remote Git repository:Git clone < git repository url >

To the staging area

  • Add the specified file:Git add 1 file 2...
  • Add a folder:Git add [folder]
  • Add all files:git add .

undo

  • To cancel a file that has been staged in the staging area:Git reset HEAD 1...
  • Hide the current change so that you can switch branches:git stash;
  • If the code is wrong and the branch is firstgit stashWhen I switch branchesgit stash popLet’s release that

Rename file

  • And submit to temporary storage area:git mv [old] [new]

Check the information

  • Query the status of all files in the current workspace:git status
  • Compare the difference between the current modified file and the staging area:Git diff
  • Directly compare all files that have been modified:git diff

submit

Git commit -m “Commit info”

Undo the last commit: git commit –amend

: git commit -a -m “Commit info”

Branch management

  • Display all branches:git branch
  • Create a branch:Git branch < branch name >
  • Create subbranch:Git checkout -b < branch name >
  • To switch to another branch:Git checkout < branch name >
  • Merge current branch with another branch:Git merge
  • Merge remote branch into current branch:Git merge < remote >/< local >
  • Delete branch:Git branch -d < branch name >
  • Add a remote repository:git remote add [remote-name] [url]Take the example of Githubgit remote add origin url
  • To push a branch of a local repository to a remote repository:Git push [branch name]Here’s an examplegit push origin master

2. Caught

Mobile terminal H5 page, view network requests, need to use tools to capture packets

Windows usually uses Fiddler

Mac OS — Use Charles all the time

Package capture + debugging tool spy-debugger

  1. Cell phone and computer with – a LAN
  2. The mobile phone agent to the computer
  3. Mobile phone browsing the web, you can capture packets

Specific use method you can go to see other big guy’s post, they speak of very good

It is recommended to use spy-Debugger to support HTTP/HTTPS without USB connection to the device

Webpack and Babel are easy to use

Why to use Webpack

  • ES6 is modular and is not supported by browsers

  • ES6 syntax, not fully supported by browsers

  • Compress code and consolidate code to make web pages load faster

Install and configure Webpack

Install NPM I -d webpack webpack- CLI

Install the local project module NPM install webpack webpack-cli -d

Configuration webpack. Config. Js

const path = require('path')

module.exports = {
  mode: 'development'.// Production environment
  entry: path.join(__dirname, '/src'.'index.js'), // Import file
  // Output the file address and name configuration
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js'}},Copy the code

After configuring the script in package.json, you can use NPM run build to run the script command

{
    "scripts" : {
		"build": "webpack"}}Copy the code

Configuring the Local Server

Install the local server NPM install webpack-dev-server -d

Configuration webpack. Config. Js

const path = require('path')

module.exports = {
  mode: 'development'.// Production environment
  entry: path.join(__dirname, '/src'.'index.js'), // Import file
  // Output the file address and name configuration
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: path.join(__dirname, "dist"),
    hot: true.port: '8080'.inline: true.open: true.overlay: true.compress: true}}Copy the code
  • Inline: The file is automatically refreshed when it changes
  • Open: Automatically opens the web page for the first time.
  • Compress: Enables gZIP compression. The type is Boolean. The default value is False
  • Overlay: whether error messages are displayed on the page. Default is false
  • Port: the port

The plug-in

Configure package.json in the script terminal enter NPM run dev to run the server

{
    "scripts" : {
		"build": "webpack"
                "dev": "webpack-dev-server"}}Copy the code

NPM install html-webpack-plugin -d

const path = require('path')
/ / import HTML - webpack - the plugin
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'development'.// Production environment
  entry: path.join(__dirname, '/src'.'index.js'), // Import file
  // Output the file address and name configuration
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: path.join(__dirname, "dist"),
    hot: true.port: '8080'.inline: true.open: true.overlay: true.compress: true
  },
  // Configure the plug-in
  plugin: {
      new HtmlWebpackPlugin({
      	// The template address
      	template: path.join(__dirname, "src"."index.html"),
        / / output name
        filename: 'index.html'}}})Copy the code

So you can package your HTML

loader

Loaders configured CSS – loader

Install NPM install style-loader css-loader -d

Then go to webpack.config.js and set it up so you can package your CSS

module.exports = {
    module: {
    rules: [{test: /\.css$/.// Regular match CSS
        use: ['style-loader'.'css-loader']  // Need to use the loader, from left to right compilation}}}]Copy the code

babel

Installation: NPM install @babel/ core@babel /preset -env babel-loader -d

Add a.babeirc file to the project directory

{
    "presets": ["@babel/preset-env"]}Copy the code

Then go to webpack.config.js and set

module.exports = {
    module: {
        rules: [{test: /\.js$/.// The regular match is js
            use: ['babel-loader'].include: path.join(__dirname,'src'),
            // Except for the node module
            exclude: /node_modules/}}}]Copy the code

Configuring the Production Environment

Create a webpack.prod.js in the project root directory

Copy and change the content of the development environment

Change mode to Production

Output file plus bundle.[Contenthash].js

const path = require('path')
/ / import HTML - webpack - the plugin
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'production'.// Production environment
  entry: path.join(__dirname, '/src'.'index.js'), // Import file
  // Output the file address and name configuration
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.[contenthash].js'
  },
  // Configure the plug-in
  plugin: {
      new HtmlWebpackPlugin({
      	// The template address
      	template: path.join(__dirname, "src"."index.html"),
        / / output name
        filename: 'index.html'}}})Copy the code

Change the build in the script in package.json to the newly created production environment webpack.prod.js

Run the package using NPM Run build

{
    "scripts" : {
		"build": "webpack"
        "dev": "webpack-dev-server"
        "build": "webpack --config webpack.prod.js"}}Copy the code

4.ES6 Modular specification

There were three previous specifications for modularity in ES6: CommonJS, AMD, CMD, and other big names

ES6 modules are designed to be as static as possible, so that the dependencies of the module and the variables in and out of the module can be determined at compile time. Both CommonJS and AMD modules can only determine these things at run time.

Here is a brief overview of the modularity specification in ES6

Modules in ES6 automatically adopt strict mode

The top layer in the ES6 module, this, points to undefined

export

Exprot must be written at the top level. The exported values are dynamically bound, not cached

The exports shown below are all in index.js

Export separately:

export let a = 'a';
export const b = 'b'
export const c = () = >{ console.log(1)}Copy the code

All at once

let a = 'a';
const b = 'b'
const c = () = >{ console.log(1)}export { a, b, c }
Copy the code

The alias is given by as when exporting

let a = 'a';
const b = 'b'
const c = () = >{ console.log(1)}export { a as lang1, b as lang2, c as lang3 }
Copy the code

import

Gets the exported element through structure assignment

import { a, b, c} from './index.js'
console.log(a)
Copy the code

You can also use aliases when importing

import { a as lang } from './index.js'
console.log(lang)
Copy the code

Import all elements

import * as lang from './index.js'
console.log(lang.a)
Copy the code

export default

You can specify the module default output

//index.js
export default function(){
  console.log('123')}Copy the code

Import The imported element can have any name

import lang from './index.js'
Copy the code

conclusion

  • Output a single value, usingexport default
  • Output multiple values, usingexport
  • export defaultWith the ordinaryexportDo not use at the same time

5. Linux command

Here I put a few commonly used, because this is my summary, their own turn out to see, so more Linux to other big guy there please check

Cp Copy file: cp -rvf a/ / TMP /

Mkdir Create a directory: mkdir dir

Ls All contents of the current directory.

Details in the ls -l directory

PWD Specifies the current directory

CD Open directory

Find file

Cat Views the contents of the file

Grep filters the content

Using the diff command, you can compare the difference between two files

Tar gz Run the tar,gzip command

The ps command displays the process/thread status

Ifconfig Displays the IP address

Ping A Network

About the Operating Environment

The runtime environment is the browser (node.js on the server)

Download the page code, render the page, and execute some JS in the process

Make sure your code is in the browser: stable and efficient

1. Page loading process

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

General flow

  1. DNS解析: domain name ->IPaddress
  2. According to the browserIPAddress to the serverhttprequest
  3. Server processinghttpRequest and return it to the browser
  4. The browser parses the rendered page
  5. Connect the end of the

Rendering process

  • According to theHTMLCode generationDOM Tree
  • According to theCSSCode generationCSSOM
  • willDOM TreeandCSSOMIntegration of strokeRender Tree
  • According to theRender TreeTo render the page
  • encounter<script>Suspend rendering, load first and executeJSCode, finish and continue
  • Until theRender TreeRender the complete

2. Window. onLoad and DOMContentLoaded

  • window.onloadExecute only when all resources have been loaded, including images
  • DOMContentLoaded DOMThe render is complete and the image may not have been downloaded yet

2. Optimize performance

Is a comprehensive question, there is no standard answer, but the requirement as far as possible comprehensive

Certain details may be asked separately: hand-writing, throttling

Just focus on the core, the interview

Performance optimization Principles

  • Use more memory, caching, or other methods
  • To reduceCPUReduce the network loading time
  • (Applicable to all programming performance optimization for a space for time)

Make loading faster

  • Reduce resource size: compress code
  • Reduce access times: Merge code (multiple JS files are merged into one file and then loaded),SSRServer side rendering, caching
  • Using a faster network:CDN
  • CSSOn thehead.JSOn thebodyAt the bottom
  • Start implementing earlyJSwithDOMContentLoadedThe trigger
  • Lazy loading (image lazy loading, slide up to load more)

Make rendering faster

  • Cache DOM queries
  • Reduce frequent DOM operations and merge them together to insert DOM structures
  • The throttlethrottleImage stabilizationdebounce

The cache

  • Static resource additionhashSuffix, calculated based on the file contenthash
  • The file content does not change, thenhashIs kept constant,urlThe same
  • urlAnd files are not changed, will automatically triggerhttpCache mechanism, return304

SSR

  • Server-side rendering: Loads and renders the web page and data together
  • nonSSR(Front and back separation) : The page is loaded, the data is loaded, and the data is rendered
  • The earlierJSP ASP PHP, now vue React SSR

Image stabilization

Listens for an input box and fires the change event when the text changes

If the keyUp event is used directly, the change event will be triggered frequently

Anti-shaking: The change event is triggered only when user input ends or pauses

// Encapsulate a shockproof function
function debounce(fn, delay = 500){
    let timer = null
    // If there is still a timer that is not executed, clear the timer and restart it below
    if(timer){
        cleartTimout(timer)
    }
    timer = seTimeout(() = >{
        fn.apply(this.arguments)
        timer = null
    },delay)
}
/ / call
const input = document.getElementById('input')
input.addEventListener('keyup',debounce(() = >{
    console.log(input.value)
},600),false)
Copy the code

The throttle

When you drag an element, you always want to get the location where the element was dragged

If you use drag events directly, they will be triggered frequently, which can easily cause a lag

Throttling: Triggers every 100ms, no matter how fast you drag

// Encapsulate a shockproof function
function throttle(fn, delay = 500){
    let timer = null
    // If there is still a timer that is not executed, the downward execution is prevented, reducing the operation
    if(timer){
        return
    }
    timer = seTimeout(() = >{
        fn.apply(this.arguments)
        timer = null
    },delay)
}
/ / call
const img = document.getElementById('img')
img.addEventListener('drag',throttle( function(e){
    console.log(e.offsetX,e.offsetY)
},600),false)
Copy the code

3. The security

The XSRF attack is briefly introduced here

  • You’re shopping, and you’re interested in something, and the item ID is 100
  • The paid interface is xxx.com/pay?id=100, but without any validation
  • I am the attacker, I took a fancy to a commodity, id is 200
  • I’m sending you an E-mail with a fascinating subject line
  • But the body of the message is hidden
  • As soon as you checked the email, you helped me buy the product with ID 200

XSRF prevention

  • Using the POST interface
  • Add authentication, such as password, SMS verification code, and fingerprint

About some old questions

+.

  • The two operands if PInumberI just add them up
  • If one of the operands is zerostring, implicitly converts the other operand tostring, and then string concatenation to get the result
  • If the operands are complex data types such as objects or arrays, concatenate both operands by converting them to strings
  • If the operand is the imagebooleanThis simple data type, then converts the operands tonumberAdd it up
  • [] + {}Because it will be cast to “, and then the + operator links –{}.{}Cast to a string"[Object Object]"
  • {}As an empty block of code,+ 0Yes Forcibly converts [] tonumber, the conversion process is+ "" + [0] = > = > 0The end result is0

Var and let const

  • varisES5Grammar,let constisES6Grammar;varVariable lift
  • varandletIs a variable and can be modified; Const is a constant and cannot be modified.
  • let constThere is block-level scope,varThere is no

Typeof Which types are returned

Typeof null // Object ()

  • string
  • number
  • boolean
  • object
  • function
  • undefined
  • symbol(ES6)

Enumeration casts and implicit casts

  • Mandatory:parseInt parseFloat toStringEtc.
  • Implicit:if,Logical operations,= =,+ Concatenation string

Handwriting depth comparison, simulating lodash isEqual

I’m not thinking about function here

// Check whether the object is an object or an array
function isObject(obj) {
  return typeof obj === 'object'&& obj ! = =null
}

// Judge all equals
function isEqual(obj1, obj2) {
  // Determine a direct comparison value that is not an array of objects
  if(! isObject(obj1) || ! isObject(obj2)) {return obj1 === obj2
  }
  // Prevent the two objects passed in from being the same object
  if (obj1 === obj2) {
    return true
  }
  // Is an object and an array (not counting function)
  // Remove keys separately
  const obj1Keys = Object.keys(obj1)
  const obj2Keys = Object.keys(obj2)
  // Select * from keys where keys are equal
  if(obj1Keys.length ! == obj2Keys.length) {return false
  }
  // Recursively judge obj2 against obj1
  for (let key in obj1) {
    const result = isEqual(obj1[key], obj2[key])
    if(! result)return false
  }
  // After traversing the recursion, it will be all equal
  return true
}

/ / use
// Pass ordinary
console.log(isEqual('123'.'123')) //true
// Pass in the same
console.log(isEqual(obj1, obj1)) //true
// Compare two identical ones
const obj1 = {
  x: 1.y: 2.s: {
    x: 1.y: 2,}}const obj2 = {
  x: 1.y: 2.s: {
    x: 1.y: 2,}}console.log(isEqual(obj1, obj2)) //true
Copy the code

The difference between split() and join()

They are a reverse operation to do

[1.2.3].join(The '-') / / '1-2-3'
'1-2-3'.split(The '-') / / [1, 2, 3]
Copy the code

What do we do with pop, push, unshift, shift

The answer is generally from these three perspectives

What is the function?

What is the return value?

Does that affect the array?

const arr = [10.20.30.40]

// pop
const popRes = arr.pop()
console.log(popRes, arr) //40 [10, 20, 30] returns the last element deleted, which changes the array

// push
const pushRes = arr.push(50)  // Append 50 to the end of the array
console.log(pushRes, arr) //4 [10, 20, 30,50] returns length to change the original array

// unshift
const unshiftRes = arr.unshift(5) // Append 5 to the beginning of the array
console.log(unshiftRes, arr) //5 [5, 10, 20, 30,50] returns length to change the original array

// shift
const shiftRes = arr.shift() // Delete the first element
console.log(shiftRes, arr) //5 [10, 20, 30, 50] returns the first element deleted, which changes the array
Copy the code

extension

Pure functions

  1. Do not change the source array (no side effects)
  2. Return an array
const arr = [10.20.30.40]

// concat
const arr1 = arr.concat([50.60.70])
console.log(arr, arr1) [10, 20, 30, 40] [10, 20, 30, 40, 50, 60, 70]

// map
const arr2 = arr.map(num= > num * 10)
console.log(arr, arr2) //[10, 20, 30, 40] [100, 200, 300, 400]

// filter
const arr3 = arr.filter(num= > num > 25)
console.log(arr, arr3) //[10, 20, 30, 40]

// Slice has no parameters in this case
const arr4 = arr.slice()
console.log(arr, arr4) [10, 20, 30, 40] [10, 20, 30, 40]
Copy the code

The pure functions

push pop shift unshift

forEach

some every

reduce

The difference between slice and splice

  • Functional differences (slice– section,splice– cutting)
  • Parameter and return value
  • Is it pure?
const arr = [10.20.30.40.50]

// Slice is a pure function
const arr1 = arr.slice() // Copy [10, 20, 30, 40, 50]
const arr2 = arr.slice(1.4) // The left is not the right [20, 30, 40]
const arr3 = arr.slice(2) // intercept index [30, 40, 50]
const arr4 = arr.slice(-3) // Reverse intercept [30, 40, 50]

// The splice impure function changes the array
const spliceRes = arr.splice(1.2.'a'.'b'.'c')
// This is a simple example, but the important thing is that it changes the array
// Start with index 1, intercept 2 elements, and replace the previous truncated space with 'a', 'b', 'c'
console.log(spliceRes, arr) //[20, 30] [10, 'a', 'b', 'c', 40, 50]
Copy the code

[10, 20, 30]. Map (parseInt)

  • mapAnd the return value
  • parseIntParameter and return value
const res = [10.20.30].map(parseInt)
console.log(res) //[10, NaN, NaN]

/ / dismantling
[10.20.30].map((item,index) = >{
    return parseInt(item,index)
})
//parseInt The second argument is optional. Represents the cardinality of the number to be parsed. The value ranges from 2 to 36.
Copy the code

What is the difference between GET and POST ajax requests?

  • getGenerally used for query operations,postOrdinary users submit operations
  • getParameter concatenation on the URL,postIn the request body (data volume can be larger)
  • Security:postEasy to preventCSRF

The differences between bind,call, and apply

Bind creates a new function that, when called, takes the value of this as the first argument and, when the new function is called, accepts a list of arguments

The call method calls a function that takes a list of parameters as the first argument, the value this

The apply method calls a function that takes the value this as the first argument and an array (or array-like object) as the second argument.

function fn(){
    console.log(this)}const newFn = fn.bind(this,p1,p2,p3)
newFn()

fn.call(this,p1,p2,p3)

fn.apply(this.arguments)
Copy the code

What is an event agent (delegate)?

An event broker is a mechanism to bind a series of inner element events to outer elements using event bubbling or event capture.

JS base 24 is written above

What are closures and what are their features? What are the negative effects?

  • Functions that have access to variables inside other functions are called closures
  • Review scopes and free variables
  • Review the closure scenario: it is passed in as an argument and returned as a return value
  • Review: Search for free variables where the function is defined (not executed)
  • Impact: Variables are resident in memory and cannot be freed. Closures are not to be messed with

How do I prevent event bubbling and default behavior?

  • event.stopPropagation()
  • Event. The preventDefault ()

How to find, add, remove, and move DOM nodes?

20.DOM node 21.DOM node operation is introduced

How to reduce DOM manipulation?

  • The cacheDOMThe query results
  • Many timesDOMOperation, merge into one – time insert

Explain how JSONP works and why it’s not really Ajax.

  • jsonpNot officially,scriptTag.
  • jsonpIs a synchronous request and only supportsgetrequest
  • ajaxthroughxhrObject to implement, supportget postCross-domain requests require back-end coordination to resolve cross-domain response headers

The difference between Document Load and Ready

  • ready, indicating that the document structure has been loaded (excluding images and other non-text media files)
  • onload, indicating that all elements of the page, including images and other files, are loaded

= =and= = =The different

  • Double equal: If the values are equal, the data type is automatically converted
  • Third class: the data type is not automatically converted. If the data types are inconsistent, false is returned, and then both values are evaluated

The difference between function declarations and function expressions

  • Function declarationfunction fn() {... }
  • Function expressionconst fn = function() {.. }
  • Function declarations are preloaded before code execution; function expressions are not

The difference between new Object(and object.create ()

  • {}Is equivalent tonew Object(), the prototype Object. The prototype
  • Object.create(nul)There is no prototype
  • Object.create(..)Specifying prototype

Scene questions about this

This is a simple example where this is determined at execution time

const User = {
    count : 1.getCount: function() {
        return this.count
    }
}
console.log(User.getCount()) //what?
const func = User.getCount
console.log( func() ) //what?
Copy the code

The first one that prints is 1

The second print is undefined because this is pointing to window

Scenarios on scope and free variables

let i
for(i = 1; i <= 3; i++) {
    setTimeout(function (){
       console.log(i) 
    },0)}//what?
Copy the code

I’m printing 4, 4, 4

The value must start with a letter and be 6 to 30 characters in length

Here we’re looking at the re

Var/reg = ^ \ [a zA - Z] $/ w {5, 29}

str.test(reg)

Hand-written string trim method to ensure browser compatibility

String.prototype.trim = function(){
    return this.replace(/^\s+/.' ').replace(/\s+$/.' ')}Copy the code

Prototype, this, the regular expression turns whitespace into an empty string

How do I get the maximum value of multiple numbers

Encapsulate Max yourself

function max() {
    const nums = Array.prototype.slice.call(arguments)// Turn the parameters into an array
    let max = 0
    nums.forEach(item= > {
        if(item > max) {
            max = item
        }
    })
    return max
}
/ / use
console.log(max(1.2.3.4.5)) / / 5
Copy the code

Use Math. Max

console.log(Math.max(1.2.3.4.5)) / / 5
Copy the code

How to implement inheritance with JS?

Prototype chain inheritance

function People() {
  this.name = 'lang'
  this.age = 21
}

People.prototype.eat = function () {
  console.log(this.name + 'eat')}function Student() {}
/ / key
Student.prototype = new People()

let lang = new Student()
lang.eat() / / lang to eat

Copy the code

Disadvantages:

Multiple instance operations on reference types can be tampered with

Inherit from the constructor

Use call to pass this directly from a subclass to the superclass

function People(name, age) {
  this.name = name
  this.age = age
  this.dd = function () {
    console.log(this.name + 'taxi')
  }
}

People.prototype.eat = function () {
  console.log(this.name + 'eat')}function Student(name, age) {
  / / directly to steal
  People.call(this, name, age)
}

let lang = new Student('lang'.21)
console.log(lang.name,lang.age) //lang 21
lang.eat() / / an error
lang.dd() / / an error
Copy the code

advantages

  • You can pass parameters
  • The properties name and age are added to the instance itself, not shared

disadvantages

  • Variables that cannot be referenced by a parent class such as the one abovedd
  • Don’t useprototypeThe variables in it are likeeat

Combination of inheritance

Combine prototype chain inheritance + borrow constructor inheritance

function People(name, age) {
  this.name = name
  this.age = age
  this.dd = function () {
    console.log(this.name + 'taxi')
  }
}

People.prototype.eat = function () {
  console.log(this.name + 'eat')}function Student(name, age, sex) {
  // Steal the structure directly
  People.call(this, name, age)
  // Add a property for yourself
  this.sex = sex
}
// Prototype chain inheritance
Student.prototype = new People()
// Add subclass methods
Student.prototype.see = function () {
  console.log(this.name + 'Can see things thousands of miles away.')}let lang = new Student('lang'.21.'male')
lang.eat() / / lang to eat
lang.dd() / / lang, take a taxi
console.log(lang.sex, lang.name, lang.age) / / male lang, 21
lang.dd = function () { // Modify the methods of your own instance and do not affect other instances
  console.log('It's changed')
}
lang.dd() // This has been changed
let jie = new Student('jie'.21.'male')
jie.dd() / / jie take a taxi
jie.see() // Jie can see things thousands of miles away
Copy the code

advantages

  • You can pass parameters
  • Properties referenced by the parent class are not shared
  • You can use a superclassprototypeThe properties of the

disadvantages

  • Added the first time the prototype chain is inheritednameageattribute
  • The second instance of the new subclass is addednameageattribute
  • The second one will override the first one according to the lookup rules of the prototype chain

Original type inheritance

This is true with less use. ES5’s object.create () can implement the following Object function

/ / treatment station
function object(obj) {
  // An empty construct
  function Fun() {}
  // The stereotype points to the passed object
  Fun.prototype = obj
  // Return the instance
  return new Fun()
}

let people = {
  name: 'lang'.age: 18.hobbys: ['book'.'music'.'learn'].eat: function () {
    console.log(this.name + 'eat')}},let lang = object(people)
lang.name = 'lang'
lang.hobbys.push('sing')
lang.eat()

let jie = object(people)
jie.name = 'jie'
jie.hobbys.push('play')
jie.eat()
// There is a problem here because it is a shallow copy and all the referenced properties are shared
console.log(lang.hobbys) // ["book", "music", "learn", "sing", "play"]

Copy the code

disadvantages

  • Can’t pass the cords
  • Because it is a shallow copy, the reference variable is shared

Parasitic inheritance

You create a function, you do a little bit of enhancement internally shallow copy is you add properties and methods to enhance the function, and then you return the construct

This is done directly with object.create ()

function createObj (obj) {
    var clone = Object.create(obj);
    // Enhance the operation
    clone.see = function () {
        console.log('see');
    }
    clone.haha = 'haha'
    return clone;
}

let people = {
  name: 'lang'.age: 18.hobbys: ['book'.'music'.'learn'].eat: function () {
    console.log(this.name + 'eat')}},/ / use
let lang = createObj(people)
Copy the code

Defect (same as original type inheritance)

  • Can’t pass the cords
  • Because it is a shallow copy, the reference variable is shared

Parasitic combination inheritance

The composition inheritance has called the construct parameter twice before

Student.prototype = new People();

Let lang = new Student('lang', 21, 'male ')

  • The first inheritance of the prototype chainStudent.prototypeaddednameageattribute
  • The second instance of the new subclass is addednameageattribute

To avoid repeated additions, we give student. prototype access to people. prototype

// Parasitic composite inheritance
function inheritPrototype(child, parent) {
  // Create a new prototype
  let prototype = Object.create(parent.prototype)
  // Make up the bug by adding constructor to point to child
  prototype.constructor = child
  // The prototype of the subclass points to the new prototype
  child.prototype = prototype
}

function People(name, age) {
  this.name = name
  this.age = age
  this.dd = function () {
    console.log(this.name + 'taxi')
  }
}

People.prototype.eat = function () {
  console.log(this.name + 'eat')}function Student(name, age, sex) {
  // Steal the structure directly
  People.call(this, name, age)
  // Add a property for yourself
  this.sex = sex
}
// Parasitic composite inheritance
inheritPrototype(Student, People)

// Add subclass methods
Student.prototype.see = function () {
  console.log(this.name + 'Can see things thousands of miles away.')}let lang = new Student('lang'.21.'male')
lang.eat() / / lang to eat
lang.dd() / / lang, take a taxi
console.log(lang.sex, lang.name, lang.age) / / male lang, 21
lang.dd = function () {
  console.log('It's changed')
}
lang.dd() // This has been changed
let jie = new Student('jie'.21.'male')
jie.dd() / / jie take a taxi
jie.see() // Jie can see things thousands of miles away
Copy the code

advantages

  • Superclass methods can be reused
  • You can pass arguments to the parent class
  • Reference properties of the parent class are not shared
  • The superclass constructor is called only once

Extends inheritance

ES6 provides calss extends Super to implement inheritance

/ / ES6 inheritance

class People {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  dd() {
    console.log(this.name + 'taxi')
  }
}

People.prototype.eat = function () {
  console.log(this.name + 'eat')}class Student extends People {
  constructor(name, age, sex) {
    super(name, age)
    this.sex = sex
  }
}

// Add subclass methods
Student.prototype.see = function () {
  console.log(this.name + 'Can see things thousands of miles away.')}let lang = new Student('lang'.21.'male')
lang.eat() / / lang to eat
lang.dd() / / lang, take a taxi
console.log(lang.sex, lang.name, lang.age) / / male lang, 21
lang.dd = function () {
  console.log('It's changed')
}
lang.dd() // This has been changed
let jie = new Student('jie'.21.'male')
jie.dd() / / jie take a taxi
jie.see() // Jie can see things thousands of miles away
Copy the code

How to catch exceptions in JS programs?

By the try… catch… capture

try {
  	//to do
}
catch (ex) {
  console.log("error", ex.message); // error oops
}finally{
    //to do
}
Copy the code

Window. onError is automatically captured

For compressed js, sourceMap will check the rows and columns of uncompressed code. For compressed JS, sourceMap will check the rows and columns of uncompressed code

window.onerror = function(message, source, linenom, colnom, error) {... }Copy the code
  • message: Error message (string)
  • source: Script URL (string) where the error occurred
  • linenom: Line number (number) where the error occurred
  • colnoM: Number of the column where the error occurred
  • error: Error object (object)

window.addEventListener('error')

window.addEventListener('error'.function(event) {... })Copy the code

What is JSON?

  • jsonIs a data format that is essentially a string
  • jsonThe format andJSConsistent object structure, rightJSMore friendly language

Gets the current page URL parameter

Traditionally, look for location.search

The new API URL SearchParams

The traditional way

// The traditional way
function query(name) {
  const search = location.search.substr(1) / / similar array. Slice (1)
  const reg = new RegExp(` (^ | &)${name}) = (/ ^ & * (& | $) `.'i')
  const res = search.match(reg)
  if (res === null) {
    return null
  }
  return res[2]
}
query('d')
Copy the code

URL SearchParams

function query(name) {
  const search = location.search
  const p = new URLSearchParams(search)
  return p.get(name)
}
console.log(query('b'))
Copy the code

willurlParameter analysis isJSobject

Srarch is analyzed in the traditional way

function queyrToObj() {
    const res = {}
    const search = location.search.substr(1)/ / intercept? The following parameters
    search.split('&').forEach(paramStr= > {
        const arr = paramStr.split('=')
        const key = arr[0]
        const val = arr[1]
        res[key] = val
    })
    return res
}
Copy the code

Using URLSearchParams

function queryToObj() {
    const res = {}
    const pList = new URLSearchParams(location.search)
    pList.forEach((val,key) = > {
        res[key] = val
    })
    return res
}
Copy the code

Flat arrays and handwritten arraysflaternConsider multiple levels

Such as there is a array [1, 2, [3, 4, [10, 20, [100, 200]]], 5]

Output: [1, 2, 3, 4, 10, 20, 100, 200, 5]

Using the concat

let arr = [1.2[3.4[10.20[100.200]]].5]
while(arr.some( item= > Array.isArray(item))){ arr = [].concat(... arr) }console.log(arr)
Copy the code

Use stringify to turn an array into a string and then regex to remove all [], divide it into an array according to, and then turn each item into a number

let arr = [1.2[3.4[10.20[100.200]]].5]
let res = JSON.stringify(arr).replace('/ \ [| \] /'.' ').split(', ').map(item= > Number(item))
console.log(res)
Copy the code

Using toString is similar

let arr = [1.2[3.4[10.20[100.200]]].5]
let res = arr.toString().split(', ').map(item= > Number(item))
console.log(res)
Copy the code

Just use ES6 flat

let arr = [1.2[3.4[10.20[100.200]]].5]
console.log(arr.flat(Infinity))
Copy the code

Write your own flatern

Array.prototype.myFlat = function() {
    function flat(){
        // Check if there is a deep array [1, 2, [3, 4]] in arR
        const isDeep = arr.some(item= > item instanceof Array)
        if(! isDeep) {return arr // Already flatern [1, 2, 3, 4]
        }

        const res = Array.prototype.concat.apply([], arr)
        return flat(res) / / recursion}}const res = [1.2[3.4[10.20[100.200]]].5].myFlat()
console.log(res)
Copy the code

Array to heavy

  • The traditional way, traversing the elements one by one to compare, go heavy
  • useSet
  • Consider computational efficiency

The traditional way

function unique(arr) {
    const res = []
    arr.forEach(item= > {
        if (res.indexOf(item) < 0) {
            res.push(item)
        }
    })
    return res
}
Copy the code

Using the Set

function unique(arr) {
    const set = new Set(arr)
    return [...set]
}
Copy the code

Handwritten deep copy

// Encapsulate the deep copy
function deepCopy(newObj, obj) {
    for (const key in obj) {
        // Retrieve each item of an object or array
        var item = obj[key];
        // Check whether the item is an object
        if (item instanceof Object) {
            newObj[key] = {};
            deepCopy(newObj[key], item);
            // Check whether the item is an array
        } else if (item instanceof Array) {
            newObj[key] = [];
            deepCopy(newObj[key], item);
            // This is a normal type of object
        } else{ newObj[key] = item; }}return newObj
}
Copy the code

Implement an immutable object

  • The object.isextensible () method determines whether an Object isExtensible(whether new properties can be added to it).

  • The object.preventExtensions () method makes an Object nonextensible, i.e. no new properties can be added, and returns the original Object.

  • The object.issealed () method determines whether an Object isSealed.

  • The object.seal () method makes an Object sealed and returns the sealed Object.

  • The object.isfrozen () method determines whether an Object isFrozen.

  • The object.freeze () method can freeze an Object.

1. Non-expandable: No new attributes can be added, and old attributes can be deleted or changed to 2. Seal: no new attributes can be added, no old attributes can be deleted, but the value can be changed to 3. Frozen: no new properties can be added, no old properties can be deleted, and no values can be changed

To introduceRAF requestAnimateFrame

  • For the animation to flow, the update frequency should be 60 frames /s, i.e16.67 msUpdate – secondary view
  • setTimeoutThe frequency is controlled manually, while the RAF browser controls it automatically
  • Background tag or hiddeniframe,RAFIt’s going to pause andsetTimeoutStill perform
  • Here we usejQuery
// For 3s, change the width from 100px to 640px, increasing the width by 540px
// 60 frames /s, 3s 180 frames, each change 3px

const $div1 = $('#div1')
let curWidth = 100
const maxWidth = 640

// setTimeout
function animate() {
    curWidth = curWidth + 3
    $div1.css('width', curWidth)
    if (curWidth < maxWidth) {
        setTimeout(animate, 16.7) // Control your own time
    }
}
animate()

// RAF
function animate() {
    curWidth = curWidth + 3
    $div1.css('width', curWidth)
    if (curWidth < maxWidth) {
        window.requestAnimationFrame(animate) // Do not control the time
    }
}
animate()
Copy the code

How to optimize front-end performance? Generally from which a few aspects to consider?

  • Principles: Use more memory, cache, less computation, and fewer network requests
  • Direction: page loading, page rendering, page smoothness