Writing in the front

As I am still a front-end rookie, so it is very likely to be wrong, warmly welcome correction!

JavaScript

What kind of language is JavaScript? What are the characteristics?

A scripting language that runs in the V8 engine of the browser and can be run directly by the interpreter without compiling. In addition, variables are loosely defined and are weakly typed.

What are some basic JavaScript specifications?

  • Do not declare multiple variables on the same line
  • Replace == with ===
  • Switch statements must have a default branch
  • Constructors start with a capital letter and constants with a capital letter
  • Use object literals instead of new Function(){}

Page Rendering principles

  • The browser parses the HTML to generate a DOMTree
  • Parsing the CSS next produces CSS ruletree
  • After parsing, the browser engine constructs RenderingTree from DOMTree and CSSRuleTree.
  • Browser call

precompiled

  • First scan the var keyword and lift it to the top;
  • Then scan the function definition before var
  • And then do it sequentially

Defer and async

  • in<script>The defer attribute in the element tells the browser to download now and delay execution. The page is parsed and executed in the specified order
  • The async property tells the browser to download now and executes as soon as the download is complete, and there is no guarantee that they will be executed in the order specified.

The data type

What are the primitive types? Is NULL an object?

Primitive types are: Boolean, string, number, null, and undefined, symbol of six.

Null is not an object, typeof NULL will output object, because previously, 32 is the system will treat the representation starting with 000 as an object, but null represents all zeros, so it is wrongly identified as object

The difference between primitive and reference types

1. Primitive types store values, and reference types store Pointers. 2. Raw data types are stored directly in the stack, and reference data types are stored in the heap.

What types can be obtained using Typeof?

undefined,string,number,boolean,object,function

Typeof can only distinguish primitive types except null, and reference types can only distinguish functions.

What is ascension? What is a temporary dead zone? Var,let and const

  • Function promotion takes precedence over variable promotion, which moves the entire function to the top of scope, and variable promotion only moves the declaration to the top of scope
  • Var is raised and can be used before declaration, let const cannot be used before declaration due to temporary dead zone
  • Var declaring variables in the global scope causes variables to be mounted on the window, but the other two do not
  • Let and const work in much the same way, but const variables cannot be reassigned
  • Let and const do not allow duplicate declarations

The original type

Why is 0.1 + 0.2! = 0.3? How to solve this problem?

In a computer, numbers are stored in binary form. In JavaScript, numbers are stored in the double precision standard of IEEE754. Due to the limited storage space, an approximate value is taken when a decimal cannot be divisible.

In 0.1+0.2, both 0.1 and 0.2 are approximate expressions, so the final result is 0.3000,0000,0000,0004 when the two approximate values are calculated. At this time, it is not approximate enough to 0.3 for JS, so 0.1+0.2 appears! = 0.3

ParseFloat ((0.1+0.2).toFixed(10)) === 0.3 // true

Null and undefined

Undefine: Indicates that a variable is declared but not assigned.

Null: The variable is defined and assigned, but is empty without any attribute methods or values

Use scenario of Symbol

Use as an attribute name

var mySymbol=Symbol();
var a={};
a[mySymbol]='hello'
Copy the code

The operator

When to use === and when to use ==

== will be converted and then compared, === will not, try to use === =.

You can use == in the following two cases

  • Determines whether an object attribute exists
Var obj = {} the if (obj. A = = null) {/ / is equivalent to obj. A = = = null | | obj. A = = = undefined}Copy the code
  • Checks whether function arguments exist
Function fn (a, b) {if (b = = null) {/ / equivalent to b = = = null | | b = = = undefined}}Copy the code

Object.is() differs from ===,==?

Object.is() is an upgrade. Object.is(NaN,NaN) returns true, and Object.is(-0,+0) returns false

Reference types

Array type

How do I know if a variable is an array?

1. Check whether there are some methods in the array

if(arr.splice){}

2. Instanceof (some IE versions are not correct)

arr instanceof Array

3.Array.isArray()

4.Object.prototype.toString.call(arr); // ‘[object Array]’

5. The constructor method

arr.constructor === Array

Convert a class array to an array

let arrayLike = {
    '0' : 'a',
    '1' : 'b',
    '2' : 'c',
    length : 3
};
let arr1 = Array.prototype.slice.call(arrayLike);
let arr2 = [].slice.call(arrayLike);
let arr3 = Array.from(arrayLike);
Copy the code

Array methods

// Pop () // end remove push() // end add shift() // start remove unshift() // start add reverse() // reverse sort() // sort splice() // Concat () // Merge array slice() // select part of array indexOf() // Find the specified element subscript in order lastIndexOf() // Find the specified element subscript in reverse orderCopy the code
// Every () checks if every item in the array meets the condition // some() checks if there are any items in the array that meet the condition // Filter () returns the array of true items // map() runs the given function on each item, Var numbers = [1,2,3,4,5,4,3,2,1]; var numbers = [1,2,3,4, 1]; numbers.every(function(item,index,array){ return item>2; }) // false numbers.some(function(item,index,array){ return item>2; }) // true numbers.filter(function(item,index,array){ return item>2; }) // [3,4,5,4,3] numbers. Map (function(index,array){return item*2; }) // [2,4,6,8,10,8,6,4,2] numbers. ForEach (function(item,index,array)Copy the code
ReduceRight () var values = [1,2,3,4,5]; values.reduce(function(prev,cur,index,array){ return prev+cur; }) // 15 // reduceRight() results the same, in reverse orderCopy the code

What sort algorithms does native Sort use?

Insert a sort algorithm combining sort and quicksort

[‘1′,’2′,’3’]. Map (parseInt)

[1,NaN,NaN]

Because parentInt requires two parameters (Val,radix),radix means analytic base, and MAP passes three (Element,index,array), the corresponding radix is illegal, resulting in parsing errors.

Date () type

Get date in 2019-02-16 format

function formatDate(dt){ if(! dt){ dt=new Date() } var year = dt.getFullYear(); var month = dt.getMonth()+1; var day = dt.getDate(); if(month<10){ month= '0'+month; } if(day<0){ day = '0'+day; } var formatDt = year+'-'+month+'-'+day return formatDt; }Copy the code

Some other methods

GetHour () // return time getMinutes() // return minutes getSeconds() // Return seconds getDay() // Return days of the week getTime() // Return millisecondsCopy the code

The Function type

Function declarations and function expressions

The parser reads the function declaration first, moving up to the top. Functional expressions, on the other hand, are not interpreted until they reach the code in which they are executed

Function sum(a,b){return a+b; Var sum = function(a,b){return a+b; }Copy the code

Talk about understanding this object

This refers to the environment object in which the function executes, always pointing to the direct caller of the function, whose value is determined at execution time

This point

1. The default binding is Window in browser and global in Node

2. Implicit binding example: window.a()

3. Explicit binding

  • Hard binding call, apply, bind
  • Context of the API call

Filter, forEach, and so on have an optional argument that is used for this value when callback is executed

4. The new binding

5. Arrow function

This is not a very detailed article, but it is recommended to see the most thorough parsing of the five this bindings in the history of JavaScript

What are the differences between bind,call and apply?

The same

  • Both are used to change the this direction of the function
  • The first argument is the value to be executed for this
  • Can be passed by subsequent parameters

The difference between

  • Call and apply call functions directly; bind returns a function that needs to be called by ()
  • Call is passed one by one. Bind is the same as call, and the second argument to apply is an array

What are the roles of Callee and Caller?

Callee is a property of the Arguments object that points to the function of the Arguments object, the current function. Recursion can be done using arguments.callee(). The arrow function has the same scope as outside of the function and no arguments object, so the arrow function has no callee

function factorial(num){
    if(num<=1){
        return 1;
    }else{
        return num*arguments.callee(num-1)
    }
}
Copy the code

Caller refers to A function that calls the current function. For example, if A calls B, b. caller refers to A(). The global scope calls the current function, whose caller value is null

Basic packing type

Number

ToFixed () returns a string representation of a numeric value in the specified decimal place

var num=10; num.toFixed(2); / / '10.00'

String

// charCodeAt() returns the character encoding of the string at the character position var STR = 'hello world'; // charCodeAt() returns the character encoding of the string at the character position. str.charAt(1); // 'e' str.charCodeAt(1); //' 101' // fromCharCode() receives the character encoding into the String string.fromcharcode (104,101,108,108,111) //'hello' // concat() concatenates the characters to get a new String var str="hello" str.concat(' world'); // "hello world" // indexOf() and lastIndexOf() return character positions // trim() remove Spaces // toLowerCase() toLowerCase,toUpperCase() toUpperCase // LocaleCompare () compares sorts according to the alphabetCopy the code

The difference between slice,substr and substring

Slice and substring receive the start and end positions, and substr receives the start position and the length of the string to be returned

For negative numbers, slice adds the negative number to the string length, substr adds the negative first argument to the string length, the second argument to 0, and SubString converts all negative numbers to 0

Split () and join()

Join () puts the elements of the array into a string, and split splits the string into arrays

Var arr = [1, 2, 3]; var str=arr.join('|'); // '1|2|3' str.split('|'); / / [1, 2, 3]Copy the code

Single built-in object

Global object

URI encoding method

EncodeURI and encodeURICcomponent encodeURI and decodeURICcomponent

What does Eval do?

The function is to parse out the JS code for string execution. Avoid eval, which is unsafe and very performance-intensive

The Math object

  • The min () and Max ()
Var Max = Math. Max (3,54,32,16); / / 54Copy the code
  • Rounding method

Math.ceil() // round up math.floor () // round down math.round () // round up

  • random()

Prototype and prototype chain

The prototype

  • All reference types (arrays, objects, functions) have a __proto__ implicit stereotype property whose value is a normal object.

In addition, object.prototype. __proto__ points to null

  • All functions have an explicit prototype property whose value is a normal object.

Function.prototype.bind() has no prototype attribute

  • __proto__ of all reference types (arrays, objects, functions) executes the prototype property of its constructor

The constructor

Constructor features: the function name starts with a capital letter, it is like a template, can create multiple instances

Var a={} // var a=new Object() var a=[] // var a=new Array() function Foo(){} // var Foo=new function (Copy the code

instanceof

Instanceof determines which constructor the reference type belongs to

F instanceof Foo: Foo. Prototype

But because __proto__ of all special objects in the prototype chain ends up pointing to Object.prototype, instanceof is not entirely accurate

What exactly does the new operator do?

  • Create an empty object
  • Points the object’s __proto to the constructor’s prototype
  • Executes the code in the constructor, passing the argument and pointing this to the object
  • Returns the object
function _new(){
    let obj = {};
    let con=[].shift.call(arguments);
    obj.__proto__ = con.prototype;
    let res = con.apply(obj, arguments);
    return res instanceof Object ? res : obj;
}
Copy the code

The difference between creating an object with new and creating it with a literal

It is more recommended to create objects in a literal manner for better performance and readability. The difference between using var o=new Object() and var o={} is that the former calls the constructor

hasOwnProperty

HasOwnProperty determines whether the object itself has a specified property and does not look up the prototype chain.

ProName Object. HasOwnProperty (proName)

It can be used to loop over objects’ own properties

for(let item in f){
    if(f.hasOwnProperty(item)){
        console.log(item)
    }
}
Copy the code

Prototype chain

When accessing an object’s properties, look in the base properties first, and if not, look up the __proto__ chain, which is the prototype chain

object-oriented

Several ways to create objects

  • The factory pattern
function createPerson(name, age){
    var o = new Object();
    o.name = name;
    o.age = age;
    o.sayName = function(){
        console.log(this.name)
    }
    return o;
}
var person1 = createPerson('chen',21)
Copy the code
  • Constructor pattern

Create object is not displayed, attribute method is assigned to this directly, no return statement

function Person(name, age){
    this.name = name;
    this.age = age;
    this.sayName = function(){
        console.log(this.name)
    }
}
var person1 = new Person('chen',21)
Copy the code

Disadvantages: Each method has to be redefined on each instance and cannot be reused

  • The prototype pattern
function Person(){}
Person.prototype.name="chen"
Person.prototype.age=21
Person.prototype.sayName=function(){
    console.log(this.name)
}
var person1 = new Person()
Copy the code

Disadvantages: All instances get the same property value

  • Hybrid constructor prototype pattern

The constructor pattern is used to define instance properties and the stereotype pattern is used to define method and shared properties.

function Person(name,age){
    this.name=name;
    this.age=age;
}
Person.prototype = {
    constructor: Person,
    sayName: function(){
        console.log(this.name)
    }
}
var person1=new Person('chen',21)
Copy the code

Implementation inheritance

JavaScript implements inheritance through prototype chains

  • Prototype chain inheritance

Core: Use an instance of a parent class as a prototype for a subclass

function Parent(){ this.name = 'parent' } Parent.prototype.sayName = function(){ return this.name } function Child(){ } Prototype = new Parent(); var child1=new Child(); child1.say();Copy the code

Advantages: Inherits templates and prototype objects from the parent class

Disadvantages: Multiple inheritance is not possible and all properties from the prototype object are shared by all instances

  • The constructor

Core: Calls the parent constructor inside the child constructor

Function Parent(){this.arr=[1,2,3]} function Child(){parent.call (this)} var child1 = new Child(); child.arr.push(4); // [1,2,3,4] child2 = new Child(); child.arr; / / [1, 2, 3]Copy the code

Advantages: solve the prototype chain inheritance in the subclass instances share the parent class reference object problem, achieve multiple inheritance, when creating subclass instances, can pass parameters to the parent class

Disadvantages: Can only inherit instance properties and methods of the parent class, not stereotype properties/methods; Function reuse is not possible, each subclass has a copy of the parent class instance function, affecting performance

  • Combination of inheritance

Using stereotype chain inheritance Using inheritance of stereotype properties and methods through constructor inheritance to achieve inheritance of instance properties

function Parent(name){ this.name = name; This.arr = [1,2,3]} parent.prototype.sayname = function(){console.log(this.name)} function Child(name,age) Parent. Call (this name), enclosing the age = age} / / Child inherit method. The prototype = new Parent () the Child. The prototype. The constructor = Child; Child.prototype.sayAge = function(){ console.log(this.age) } var child1=new Child('chen',21); child1.arr.push(4); //[1,2,3,4] child1.sayname () // 'Chen' child1.sayage () // [1,2,3] child2.arr // "miao" child2.sayAge() //Copy the code

Advantages: make up for the defects of constructor inheritance, can inherit instance attribute/method, can also inherit prototype attribute/method, there is no reference attribute sharing problem, can pass parameters, reusable

Disadvantages: Calls the parent constructor twice, once to create the subtype stereotype and once inside the subconstructor, generating two instances (the subclass instance hides the subclass stereotype)

  • Primary inheritance

Core: Performs a shallow copy of a given object

Var person = {name: 'Chen ', arr: [1,2,3]} var person1 = object.create (person); person1.name = 'run' person1.arr.push(4) var person2 = Object.create(person); person2.name = 'miao' person2.arr.push(5) person.arr; / / [1, 2, 3, 4, 5]Copy the code

Disadvantages: All instances inherit properties from the stereotype; Unable to reuse

  • Parasitic inheritance

Core: Create an object based on an object, enhance the object, and return the object.

Function create(original){var clone = object(original); SayHi = function(){console.log('hi')} return clone; } var person = { name: 'chen' } var person1 = create(person); person1.sayHi();Copy the code
  • Parasitic combinatorial inheritance
function Parent(name){ this.name = name; Parent.prototype.sayName = function(){console.log(this.name)} // Function Child(name,age){// Inherit attributes parent.call (this, name) this.age=age } function inheritPrototype(Child, Parent){ var prototype=Object.create(Parent.prototype); prototype.constructor=Child; Child.prototype=prototype; InheritPrototype (Child, Parent); Child.prototype.sayAge=function(){ console.log(this.age) } var child1=new Child('chen',21); child1.arr.push(4); SayName (); sayAge(); var child2=new Child(' Miao ', [1,2,3] child2.arr // "miao" child2.sayAge() //Copy the code

How does class implement inheritance, and what is the nature of class?

Class is just syntactic sugar, essentially a function

class Parent{
    constructor(value){
        this.val=value
    }
    getValue(){
        console.log(this.val)
    }
}
class Child extends Parent{
    constructor(value){
        super(value)
        this.val = value
    }
}
let child = new Child(1)
child.getValue() // 1
child instanceof Parent // true
Copy the code

Core: Extends indicates which Parent class it inherits from, and super must be used in the subclass constructor, which can be thought of as parent.call (this,value)

What are object-oriented programming and procedural programming, their similarities and differences, their strengths and weaknesses

Process oriented is to analyze the steps needed to solve the problem, and then use functions to implement these steps step by step, when using the call one by one

Object orientation is the decomposition of the transactions that constitute the problem into objects, and the purpose of rewarding objects is not to complete a step, but to describe the behavior of something in the whole step of solving the problem.

Advantages: easy maintenance, high readability, easy to expand, high inheritance, reduce the amount of repeated work, shorten the development start

closure

A closure is a function that has access to variables inside another function. When other functions are defined inside a function, a closure is created

Talk about your understanding of closures

Block-level scopes can be modeled using closures

Advantages: Can avoid global variable pollution, encapsulation and cache;

Disadvantages: Closures are resident in memory, increasing memory usage and causing memory leaks. Workaround: Before exiting the function, set invalid local variables to NULL.

Closures have two main uses: 1. They can read variables inside functions; 2. 2. Keep these variables in memory at all times. 3. Encapsulate the private properties and methods of the object

Explain your understanding of scope chains

The function of the scope chain is to ensure that the variables and functions in the execution environment are in order. The variables in the scope chain can only enjoy access, and the access to the window object is terminated.

Simply put, a scope is the accessible scope of variables and functions

How do I create block-level scopes

  • ES6 uses let and const
  • closure

BOM

What are BOM objects?

  • Window JS topmost object
  • Location Indicates the current URL of the browser
  • The Navigator browser itself
  • Screen Indicates the screen information of the client
  • The history browser accesses historical information

Window object method

alert(),prompt(),confirm(),open(),close(),print(),focus(),blur(),moveBy(),moveTo(),resizeBy(),resizeTo(),scrollBy(),scro llTo(),setInterval(),setTimeout(),clearInterval(),clearTimeout()

The history object

history.go(-1); // go(1); // forward a page history.back(); // back a page history.forward(); // Move forward one pageCopy the code

The window position

  • Get the left and top positions of the window across the browser
var leftPos=(typeof window.screenLeft == 'number') ? window.screenLeft : window.screenX;
var topPos=(typeof window.screenTop == 'number') ? window.screenTop : window.screenY;
Copy the code
  • Moves a window to the specified position

MoveTo (): receives the x and y coordinates of the new position

MoveBy (): Receives the number of pixels moving in horizontal and vertical directions

The window size

OuterWidth and outerHeight return the size of the browser window itself, while innerWidth and innerHeight return the size of the container view area

  • Resize the window

ResizeTo () and resizeBy ()

How do I detect browser types

Use the navigator userAgent

var ua = navigator.userAgent;
var isChrome = ua.indexOf('Chrome')
Copy the code

Unpick the parts of the URL

Use the location property

  • Href Full URL address
  • Protocol agreement
  • Host Host name + port number
  • The hostname hostname
  • Port the port number
  • Pathname Relative path
  • Hash # anchor point
  • search ? Query string
history.go(1)
Copy the code

DOM

Why is DOM manipulation slow?

Because DOM belongs to the rendering engine, and JS belongs to the JS engine, when we manipulate the DOM through JS, it involves communication between two threads, and manipulating the DOM can lead to redraw backflow, thus causing performance problems.

Insert tens of thousands of DOM, how to achieve page free lag?

  • 1. Render the DOM partially in batches, using requestAnimationFrame to loop in the DOM
  • 2. Virtual scrolling, rendering only the content within the viewable area

What happens when rendering is blocked

  • 1. Both HTML and CSS block rendering. If you want to render fast, you should reduce the file size of the initial rendering, flatten the hierarchy, and optimize the selector
  • 2. The browser pauses DOM construction when script tags are parsed.

Solutions:

  • ① Place the script tag at the bottom of the body
  • ② Add the defer attribute to the script tag. The JS file will be downloaded in parallel but executed sequentially after the HTML has been parsed
  • 3. Script tag with async property means JS file download and parsing does not block rendering

Repaint and Reflow

Redraw is when nodes change style without affecting the layout, and backflow is when layout or geometry properties need to change

Backflow is bound to redraw, and the cost of backflow is high

Performance issues: 1. Change window size 2. Change font 3. Text change 5. position or float 6. box model

Reduce redrawing and reflow

  • 1. Use transform instead of top
  • 2. Use visibility instead of display: None. The former will only cause redraw and the latter will cause backflow
  • 3. Do not put node property values in a loop as variables in the loop
  • 4. Don’t use a table layout
  • 5. The faster the animation is implemented, the more backflows there are. RequestAnimationFrame can also be used
  • 6.CSS selectors are matched from right to left to avoid too many nodes
  • 7. Set the nodes that are frequently redrawn or reflow as layers

① Will-change attribute ② Video, iframe label

Create a node

  • CreateElement Creates an element
  • CreateTextNode Creates a text node
  • CreateDocumentFragment Creates a document fragment
  • CloneNode returns a copy of the node that called the method

Matters needing attention:

  • The above is just creating an isolated node that needs to be added to the document through appendChild
  • CloneNode pays attention to whether the node being copied contains child nodes and event bindings
  • Use createDocumentFragment to solve performance problems when adding a large number of nodes

Page modification API

  • AppendChild () adds child nodes
  • InsertBefore () adds the node before the reference node

ParentNode. InsertBefore (newNode, refNode) parentNode indicates the parentNode, newNode indicates the node to be added, and refNode indicates the reference node

  • RemoveChild () removes child nodes
  • The replaceChild () replacement

parent.replaceChild(newChild,oldChild)

Node Query API

  • document.getElementById
  • document.getElementsByTagName
  • document.getElementsByName
  • document.getElementsByClassName
  • Document.queryselector // returns the first matched element
  • document.querySelectorAll

Node-relational APIS

  • ParentNode // parentNode
  • ParentElement // The parent node, which must be element
  • ChildNodes // List of child elements, containing text, comment nodes
  • Children // List of child elements
  • FirstChild // firstChild
  • LastChild // the lastChild
  • HasChildNodes // Checks whether the current node has children
  • PreviousSibling // previousSibling node
  • PreviousElementSibling // Previous sibling node
  • NextSibling // nextSibling node
  • NextElementSibling // Next sibling element node

Element attribute API

  • SetAttribute Sets the attribute

element.setAttribute(name, value)

  • GetAttribute Returns the attribute value
  • RemoveAttribute Deletes an attribute

Element Style API

  • Window.getcomputedstyle returns the computed style of the element
  • GetBoundingClientRect returns the size of the element and its position relative to the browser’s visible window
  • Modify the style of the element directly
ele.style.color = 'red'
ele.style.setProperty('font-size', '16px')
ele.style.removeProperty('color')
Copy the code
  • Add style rules dynamically
var style = document.createElement('style'); style.innerHTML='body{color:red; } #top{color:white; } '; document.head.appendChild(style);Copy the code

What’s the difference between attribute and property?

Attributes are attributes that A DOM element owns in a document as an HTML tag

Prototype is the attribute that the DOM element has as an object in JS

How does JS set the width and height of the fetch box model pair?

  • Gets the width and height of the inline element

dom.style.width/height

  • Only available in IE to get element width and heightdom.currentStyle.width/height
  • Get element width and height, good compatibilitywindow.getCompontedStyle(dom).width/height
  • Gets the width and height based on the element’s absolute position in the window

dom.getBoundingClientRect().width/height

  • Most commonly used, best compatibility

dom.offsetWidth/offsetHeight

OffsetWidth/offsetHeight, clientWidth/clientHeight srcollWidth/scrollHeight difference

  • Return content+padding+border with equetboundingClientRect ()
  • ClientWidth /clientHeight returns a content+padding and no scroll bar, if any
  • ScrollWidth /scrollHeight returns the size containing content+paddin+ overflow

Difference between document.write and innerHTML

  • Document.write can only redraw the entire page
  • InnerHTML redraws a part of the page

DOM events

Level of DOM events

  • DOM0 element.onclick=function(){}
  • DOM2 element.addEventListener('click',function(){},false)
  • DOM3 element.addEventListener('keyup',function(){},false)

Dom0-level events assign a function to an event handler property, with the disadvantage that a handler cannot bind multiple handlers at the same time.

Dom2-level event running adds multiple handlers to a program. It defines two methods, addEventListener and removeEventListener, which are used to bind and unbind events respectively. The method contains three parameters: the attribute name of the bound event handler, the handler function, and whether to execute the event at capture time

IE8 below uses attachEvent and detachEvent and does not need to pass in a third parameter because IE8 below only supports bubbler events

btn.attachEvent('onclick', showFn);
btn.detachEvent('onclick', showFn);
Copy the code

The DOM3 level is at level DOM2 events on the basis of adding a lot of event types such as load, scroll, blur, focus, dbclick, mouseup, mousewheel, (, keydown, keypress, It also allows users to customize some events.

How are events used?

  • HTML event handler
<div onclick="clicked()"></div>
Copy the code

Pros and cons: Simple, but tightly coupled to HTML code, not easy to change

  • DOM0 level handler
document.onclick = function(){}; // Docuemtn. onclick = null; // Delete the eventCopy the code

Pros and cons: simple and cross-browser

  • DOM2 level handler
AddEventListener ('click', function(){}, Boolean) removeListener('click', function(){}, Boolean) // Remove the eventCopy the code

Pros and cons: You can add more than one listener. If you specify an anonymous handler, you cannot remove it

  • IE event handler
AttachEvent ('onclick', function(){}) // detachEvent('click', function(){}Copy the code

Pros and cons: You can add more than one listener. If you specify an anonymous handler, you cannot remove it

Differences between IE and the standard DOM event model

  • Parameter difference:

The first argument to attachEvent() is one more “on” than the event name of addEventListener(); And there is no third parameter, because the IE event model only supports bubbling event streams

  • Event handler scope:

The event handler in IE is globally scoped, where this points to the window, whereas the DOM event model is applied to the element where this executes the element to which it belongs

  • Attribute methods of the event object

To prevent a bubble

IE: cancelBubble = true

DOM: stopPropagation()

Block element default events

IE: returnValue = false

DOM: the preventDefault ()

Event goals

IE: srcElement DOM: target

What compatibility does IE have with standards?

var ev = ev || window.event;
document.docuemntElement.clientWidth || document.body.clientWidth
var target = ev.srcElement || ev.target
Copy the code

DOM event model (bubbling and capturing)

  • The event bubbling

The third parameter addEventListener is false. The event is executed while bubbling up. The target of the event bubbles up one level at a time

How do I prevent events from bubbling up

Child.addeventlistener ('click', function(e){console.log(' destination events ') e.topPropagation (); }, false)Copy the code
  • Event capture

Event capture is performed from the top down, setting the third addEventListener parameter to true

The DOM event flow

The event flow specified by DOM2 level events consists of three phases: event capture phase, in target phase and event bubbling phase. Event capture is sent first, providing an opportunity to intercept the event, followed by the actual target receiving the event, and finally the bubbling phase, where the event can be responded to

Capture the specific flow of DOM event capture

window->docuemnt->html->body->…

First the window receives the event, then the Window goes to the document, then the HTML tag, then the body, and then down the hierarchy. The equivalent is bubbling, the process from the current element to the window

Common uses of the Event object

  • Event.preventdefault (): Prevent the default event
  • Event.stoppropagation (): Prevents bubbling
  • Event. StopImmediatePropagatio () : stop the rest of the event handling function execution, and prevent the current event bubbling on the DOM
  • Event. currentTarget: The event element currently bound when an event delegate occurs
  • Event. target: Identifies which element is currently clicked when an event delegate is performed

Custom events

var event = new Event('custome');
ev.addEventListener('custome', function(){
    console.log('custome');
});
ev.dispatchEvent(event);
Copy the code

The difference between mouseover and MouseEnter

Mouseover: Events are triggered when the mouse moves over an element or its child, so there is a repetitive, bubbling process. The corresponding remove event is mouseout

Mouseenter: An event is triggered when the mouse moves over the element itself (without child elements), without bubbling. The corresponding remove event is mouseleave

Please explain what event broker is?

The event broker (event delegate) delegates events that would otherwise be bound to the parent element, which acts as the event listener. The principle is that events bubble up in DOM elements.

Benefits: Improved performance, significant memory savings, reduced event registration, and no need to bind new child objects again

The difference between document.load and document.ready

Document.onload is executed after the style structure has been loaded, window.onload() not only executes after the style structure has been loaded but also after all the style image resource files have been loaded

Document.ready does not have this method in the native document.ready. JQuery has $().ready(). The ready event does not require the page to be fully loaded.

JSON

How to understand JSON?

JSON is a built-in object of JS and a lightweight data interchange format. Two methods are commonly used:

  • Parse // String to object
  • Stringify // Object to string

The difference between XML and JSON?

  • Data volume: JSON is smaller and faster than XML.
  • Data interaction: JSON and JavaScript interaction is more convenient, easier to parse, better data interaction
  • Data description: JSON is less descriptive of data than XML
  • In terms of transfer speed: JSON is much faster than XML

Ajax

How do YOU create Ajax?

Var XHR = new XMLHTTPRequest (); // Create a new HTTP request xhr.open("get", url, Xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200){// Alert (xhr.responseText)}}} // Send the HTTP request xhr.send(null);Copy the code

Status code readyState: 0: not initialized, send() is not called. 1: send() has been called and a request is in progress. 2: The send() method is executed and all responses are received. 3: The response is being parsed. 4: Parses are complete and can be invoked on the client

What are the pros and cons of Ajax?

Advantages: 1. Improves user experience through asynchronous mode. 2. Optimized the transmission between browser and server to reduce unnecessary data round-trip and reduce bandwidth consumption; 3.Ajax runs on the client side, taking part of the work originally undertaken by the server and reducing the server load under a large number of users; 4.Ajax can implement partial refresh

Disadvantages: 1.Ajax exposes the details of the server interaction; 2. Weak support for search engines; 3. Not easy to debug

The difference between GET and POST implementations in browsers

  • GET back refresh harmless, bookmark, can be cached, parameters will be retained in the browser history, only ASCII characters are allowed, poor security, data display in the URL
  • POST backward refresh will resubmit data, cannot be bookmarked as a label, cannot be cached, parameters will not be saved in the browser history, the data type is unlimited, better security, data will not be displayed in the URL

Error of GET request parameter transmission

Myth: We often think of GET request parameters as limited in size and POST as unlimited

In fact, HTTP protocol does not limit the length of GET/POST requests. The maximum length of GET is limited because browsers and WEB servers limit the length of urls.

GET and POST

There is no difference between THE GET and POST methods, but the packet formats are different.

Cross domain

Three tags that can cross domains:

What is cross-domain?

Cross-domain refers to data incoming or communication between different domains through JS. Protocol, domain name, port one difference is different domains

Why do browsers use the same Origin policy?

The same origin policy is used to prevent CSRF attacks. It uses the login status of users to initiate malicious requests. Without the same-origin policy, web sites can be accessed by Ajax content from any source.

How to solve cross-domain problems?

  • JSONP

The principle is to exploit the vulnerability that

function jsonp(url, callback, success){
    let script = docuemnt.createElement('scipt');
    script.src = url;
    script.async = true;
    script.type = "text/javascript";
    window[callback] = function(data){
        success && success(data)
    }
    document.body.appendChild(script)
}
jsonp('http://xxx.com', 'callback', function(value){
    console.log(value);  
})
Copy the code

JSONP is simple to use and compatible but only for GET requests

  • CORS

To enable CORS, set access-Control-origin on the server. This attribute indicates which domain names can Access resources. There are simple requests and complex requests. Complex requests have one more precheck request

  • Document.domain only applies to secondary domain names like, for examplea.test.comandb.test.com. Add to the pagedocument.domain = 'test.com'Indicates that the same secondary domain name can cross domains
  • postMessage

Typically used to retrieve data from a third party page embedded in a page, one page sends a message and the other determines the source and receives the message

/ / send a message window. The parent. PostMessage (' message ', 'http://www.test.com') // Let MC =new MessageChannel() Mc.addeventlistener ('message', event => { let origin = event.origin || event.originalEvent.origin; If (origin = = = 'http://www.test.com') {the console. The log (' validation by ')}})Copy the code
  • window.name

storage

Please describe the difference between cookie, sessionStorage and localStorage

A:

  • Capacity: Cookie only 4KB, localStorage and sessionStorage maximum capacity of 5M
  • Server communication: Cookies are used for communication between the client and the server
  • Valid time: cookies exist before the set valid time expires, sessionStorage closed the current page will be cleaned, localStorage will exist unless actively deleted
  • API ease of use: The COOKIE API needs to be encapsulated before it can be used. Localstorage.setitem (key,value); localStorage.getItem(key)

How many ways can storage be implemented?

Cookie, sessionStorage and localStorage, indexDB.

IndexDB has unlimited storage size, does not communicate with the server, and persists unless deleted.

What is a Service Worker?

A Service Worker is an independent thread running behind the browser. It can be used for caching. The transport protocol must be HTTPS

Server Worker’s job?

  • Interacting with the cache, when a user requests something in the cache, the Service Worker can immediately retrieve the data from the cache without making an external HTTP call
  • Send push Notifications
  • Running background synchronization: When a file is sent from a browser while offline, the Service Worker can save the task and upload the file to an external server when the network connection is restored

ES6

Arrow function

Differences between arrow functions and normal functions:

  • Arrow functions have no arguments (use residual operators instead)
  • Arrow functions have no prototype and cannot be used as constructors (cannot be called with the new keyword)
  • Arrow functions do not have their own this, but refer to the this of the outer execution context

Extended operator

  • You can turn a class array into a real array
let nodeList = document.querySelectorAll('div')
let arr=[...nodeList]
Copy the code
  • Merging multiple arrays
Let arr1 = [1, 2, 3] let arr2 = [4 and 6] let arr3 = arr2] [... arr1,...Copy the code

for… Of circulation

The difference between for-of and for-in

  • A for-of traversal gets the key value of the object, and a for-in gets the key name
  • For-in traverses the entire prototype chain of an object. Of only traverses the current object, not the prototype chain
  • For array traversal, for-in traverses all enumerable properties (including prototype chains), for… Of returns only the value of the property corresponding to the array index

for… Of the principle of

Using the iterator interface inside the iterator object, for… The of loop decomposes into the primitive for loop

What are the pros and cons of understanding promise? What is the Promise chain? What is the difference between Promise constructor execution and THEN execution?

  • Promise has three states: Pending, Resolved, and Rejected

Once the wait state changes to another state, it cannot change again

  • When you build a Promise, the code inside the constructor executes immediately.
  • Promise implements chained calls that return a new Promise after each call to THEN. If you use return in then, the value of return will be wrapped in promise.resolve ()

What do you mean by Generator?

The Generator can control the execution of functions

function *foo(x){ let y=2*(yield(x+1)) let z=yield(y/3) return (x+y+z) } let it=foo(5) it.next() // {value:6,done:false}  it.next(12) it.next(13)Copy the code

A Generator call returns an iterator. The first time next, the function stops at yield(x+1) so value=5+1=6; The second time, next, the argument is passed equivalent to the yield value, that is, let y=2*12=24; let z=24/3=8; The third time, next, we pass in arguments equivalent to the yield value of the previous one, that is, let z=13,y=24,x=5, which together return 42

Advantages of async,await over Promise

  • The advantage is that you can write code more clearly and accurately by handling the then call chain
  • Disadvantages: Await modifies asynchronous code to synchronous, and performance degrades if multiple asynchronous code uses await without dependencies between them

Understanding of async, await, internal principle

Resolve () is used to wrap the return value of a function in promise.resolve (), as in then, and async can only be used with await. Await is generator plus Promise sugar. And the internal implementation of automatic execution generator

What is the distinguishing feature of setTimeout and setInterval, requestAnimationFrame each?

SetTimeout delays execution and setInterval executes the callback function at intervals. RequestAnimationFrame has the function throttling function and the delay effect is accurate

Fulfill a Promise yourself

const PENDGIN='pending' const RESOLVED='resolved' const REJECTED='rejected' function myPromise(fn){ const that=this that.state=PENDING that.value=null that.resolvedCallbacks=[] that.rejectedCallbacks=[] function resolve(value){ if(value  instanceof myPromise){ return value.then(resolve, reject) } setTimeout(()=>{ if(that.state===PENDING){ that.state=RESOLVED; that.value=value; that.resolvedCallbacks.map(cb => cb(that.value)) } },0) } function reject(error){ setTimeout(()=>{ if(that.state===PENDING){ that.state=REJECTED that.value=value that.rejectedCallbacks.map(cb => cb(that.value)) } },0) }  try{ fn(resolve, reject) }catch(e){ reject(e) } } myPromise.prototype.then=function(onFulfilled, onRejected){ const that=this onFulfilled=typeof onFulfilled==='function'? onFulfilled: v=>v onRejected=typeof onRejected==='function'? onRejected: r=>{throw r} if(that.state===PENDING){ that.resolvedCallbacks.push(onFulfilled) that.rejectedCallbacks.push(onRejected) } if(that.state===RESOLVED){ onFulfilled(that.value) } if(that.state===REJECTED){ onRejected(that.value) } } new myPromise((resolve, reject) => { setTimeout(()=>{ resolve(1) },0) }).then(value=>{ console.log(value) })Copy the code

The difference between threads and processes

A process describes the events required by the CPU to run an instruction and load and save the context. A thread is a smaller unit, the second is the time it takes to execute an instruction

JS single thread benefits

Because JS can modify the DOM, the UI thread cannot render the UI safely if js executes a process that is still working. JS single thread running, can achieve memory saving, save context switching time, no lock problem

What is an execution stack

Implement the stack structure for storing function calls, following the principle of first in, last out. Start at the bottom of the stack and then take execution out of the top of the stack

Microtasks and macro tasks

Different task sources will be assigned to different task queues. Task sources can be divided into microtasks and macrotasks. Microtasks include Process. nextTick, promise, MutationObserver. SetTimeout, setInterval, setImmediate, I/O, UI rendering

EventLoop Execution sequence

Execute synchronous codes first, which is a macro task. 2. After all synchronous codes are executed, the execution stack is empty. Perform all microtasks 4. When all microtasks have been performed, page 5 will be rendered if necessary. Then start the next EventLoop, which executes the asynchronous code in the macro task, the callback function in setTimeout

Proxy

One of the core features of Vue3.0 is to use a Proxy instead of an Object. A defineProperty Proxy can put an interceptor in front of a target Object

The shortage of the Object. DefineProperty

Cannot detect addition and deletion of object root property 2. Cannot detect subscription-based changes to array 3. Unable to detect monitoring of. Length changes

References:

JavaScript Advanced Programming (version 3)

Yck – The Way to the front End interview

Nearly 10,000 words ES6 grammar knowledge supplement