What is a compiled language? What is interpreted language?JSWhat kind of language is it?

1. Compiled languages

1. Explain

Before the program is executed, a special compilation process is required to compile the program into a machine language file. When the program is run, it does not need to be re-translated. The compiled results are used directly.

2. The advantages and disadvantages of

The program execution efficiency is high, the compiler is dependent, the cross-platform is poor.

3. For example

C and C++ are compiled languages.

2. Interpreted language

1. Explain

The program does not need to be compiled. The program is translated into machine language at runtime, once per execution.

2. The advantages and disadvantages of

Interpreted languages are less efficient and cannot be run without an interpreter, but they are easier to cross platform by providing a specific interpreter.

3. For example

Python and JS are both interpreted languages.

Cast & Implicit cast

1.JSWhat are the castings and implicit casts in the

1. Cast a type

  • String()
  • Number()
  • Boolean()
  • parseInt()
  • parseFloat()

2. Implicit type conversion

  • + stringConverted to digital
  • a + " "Convert to string
  • ! varConvert to a Boolean value

Basic data types and reference data types

1, the difference between

1. As an argument to a function:

  1. A primitive data type is passed a copy of the data, and changes to the original data do not affect the incoming data.
  2. Reference data types pass in the reference address of the data, and changes to the original data affect the incoming data.

2. Storage location in memory:

  1. Basic data types are stored in the stack.
  2. The reference data type stores a pointer in the stack, and the data entity to which the pointer points is stored in the heap.

2. Stack and heap allocation in memory

eg:var a = {name: 'yuhua'}Variable storage

  1. Put this code inCode Segment;
  2. The variableaIn theStack: local variables and Pointers;
  3. will{name: 'yuhua'}In theHeapTotal: Object, closure.

3,symbol

1. symbolHow do I get the key name of an object?

Can’t getsymbolKey:

  1. for infor ofYou don’t get it in the loopsymbolKey;
  2. Object.keys(),Object.getOwnPropertyNames(),JSON.stringify()Method cannot getsymbolKey;

Can getsymbolKey:

  1. Object.getOwnPropertySymbols()Method can be fetched and returns an array;
  2. Reflect.ownKeys()You can get all key names, includingsymbol

2. symbolType conversion

1) can be converted tostring
const symbolKey = Symbol(123)
String(symbolKey) // "Symbol(123)"
symbolKey.toString() // "Symbol(123)"
Copy the code
2) Can be converted to a Boolean value
Boolean(symbolKey) // true
Copy the code
3) Cannot be converted to a number (error)
Number(symbolKey)
Uncaught TypeError: Cannot convert a Symbol value to a number
    at Number (<anonymous>)
    at <anonymous>:1:1
Copy the code
4) Convert to objects
b = Object(symbolKey)
Symbol {Symbol(123)}
  description: "123"
  __proto__: Symbol
    constructor: ƒ Symbol(a)description: "123"
    toString: ƒ toString ()valueOf: ƒ the valueOf ()Symbol(Symbol. ToPrimitive) : ƒ [Symbol.toPrimitive]()
    Symbol(Symbol.toStringTag): "Symbol"Get the description: ƒ description ()__proto__: Object
    [[PrimitiveValue]]: Symbol(123)
typeof b // "object"
b.constructor() // Symbol()
b instanceof Symbol // true
b instanceof Object // true
Object.prototype.toString.call(b) // "[object Symbol]"
Copy the code

4, string transformation function

1. eval()

let funcStr = "function test(value){alert(value)}";
let test = eval("(false || "+funcStr+")");
test("Function can execute.");
Copy the code

2. new Function()

function add(a, b) {
  return a + b;
}
/ / equivalent to the
var add = new Function ('a'.'b'.'return a + b');
let funcStr = "function test(value){alert(value)}";
let funcTest = new Function('return '+funcStr);
funcTest()("Functions can also execute.")
Copy the code

Four,nullundefinedThe difference between

1.Null

  • nullRepresents a “none” object, converted to a value of0;
  • As an argument to a function, indicating that the argument to the function is not an object;
  • As the end point of the object prototype chain.
  • Number(null)0
  • 5 + null5

2,Undefined

  • The variable is declared, but not assigned, is equal toundefined;
  • When the function is called, the argument that should be provided is not provided, which is equal toundefined;
  • Object has no assignment property, which has a value ofundefined;
  • Function returns no value by defaultundefined;
  • Number(undefined)NaN;
  • 5 + undefinedNaN.

Five,typeofinstanceofThe difference between

1. Major differences

  • typeofRepresents the detection of a variable type, except for the basic data typenullAre normally displayed as their corresponding types, except for reference typesfunctionAll the others will be displayed asobject;
  • instanceofTest whether the stereotype object of a constructor is in the stereotype chain of an object.

2,typeofnullError display

This is just a long-standing Bug in JS. In the original version of JS, the 32-bit system was used. For performance purposes, the type information of variables was stored in low order. The beginning of 000 represents an object, while null represents all zeros, so it was wrongly identified as object.

3. Implement oneinstanceof

Object.getprototypeof () : The object.getPrototypeof () method returns the Prototype of the specified Object (the value of the internal [[Prototype]] property).

function myInstance (left, right) {
	let proto = Object.getPrototypeOf(left) // The object.getPrototypeof () method returns the specified Object's Prototype (the value of the internal [[Prototype]] property).
  	while(true) {
  		if (proto === null) return false
	    if (proto === right.prototype) return true
    	proto = Object.getPrototypeOf(proto)
  	}
}
Copy the code

validation

myInstance([], Object) //true
myInstance(Map.Object) //true
myInstance(new Map(), Object) //true
myInstance(Map.Function) //true
myInstance(class {}, Function) //true
myInstance(1.Number) //true
myInstance('1'.String) //true
Copy the code

Vi.this

1. Describethis

For functions, the object that refers to the last call to the function is an internal object automatically generated when the function is running and can only be used inside the function. Globally, this points to window.

2. Inside the functionthisWhen was it determined?

When a function is called, it points to the object that was last called

3,call,apply,bindThe difference between the three

All three functions bind the function to its context, changing the reference to this in the function; The difference between the three is the difference in grammar.

fun.call(thisArg[, arg1[, arg2[, ...]]])
fun.apply(thisArg, [argsArray])
var bindFn = fun.bind(thisArg[, arg1[, arg2[, ...]]])
bindFn()
Copy the code

The difference between Apply and Call is that the call method accepts a list of arguments, while apply accepts an array of arguments. The bind() method, on the other hand, creates a new function, sets its this keyword to the supplied value when called, and provides a given sequence of arguments before any supply when the new function is called.

const name = 'window'
const sayName = function (param) {
    console.log('my name is:' + this.name + ',my param is ' + param)
}
sayName('window param') //my name is:window,my param is window param

const callObj = {
    name: 'call'
}
sayName.call(callObj, 'call param') //my name is:call,my param is call param

const applyObj = {
    name: 'apply'
}
sayName.apply(applyObj, ['apply param']) //my name is:apply,my param is apply param

const bindObj = {
    name: 'bind'
}
const bindFn = sayName.bind(bindObj, 'bind param')
bindFn() //my name is:bind,my param is bind param
Copy the code

4, What are the directions of this?

  1. Default binding: in the global environment,thisDefault binding towindow.
  2. Implicit binding: Generally, when a function call is contained by a direct object, also called a method call,thisImplicitly bind to the direct object.
  3. Implicit loss: Implicit loss is when an implicitly bound function loses its binding object and thus defaults towindow. Explicit binding: Passedcall(),apply(),bind()Method to bind an object tothisIs called explicit binding.
  4. newBinding: If a function or method call is preceded by a keywordnew, which constitutes a constructor call. forthisFor binding, theta is thetanewBinding.

5. Arrow functionthis

  1. The arrow function is not therethis, so you need to find the scope chain to determinethisWhich means that if the arrow function is contained by a non-arrow function,thisIt’s bound to the nearest non-arrow functionthis.
  2. Arrow functions don’t have their ownargumentsObject, but can access peripheral functionsargumentsObject.
  3. Can’t passnewKeyword call, again nonew.targetValues and prototypes.

6. Manual implementationcall,applybind?

1. call

Function.prototype.myCall = function (thisArg, ... args) {
    const fn = Symbol('fn') // Declare a unique symbol attribute to prevent fn from overwriting an existing attribute
  	thisArg = thisArg || window // If this is not passed, the window object is bound
  	thisArg[fn] = this // This refers to the object that called the call
  	constresult = thisArg[fn](... args)// Execute the current function
  	delete thisArg[fn] // Delete our declared fn
  	return result // Return the result of function execution
}
Copy the code

2. apply

Function.prototype.myApply = function (thisArg, args) {
    const fn = Symbol('fn') // Declare a symbol
  	thisArg = thisArg || window / / set thisArg
  	thisArg[fn] = this // this points to change
  	constresult = thisArg[fn](... args)// Execute the function
  	delete thisArg[fn] / / delete the fn
 	return result // Return the result
}
Copy the code

3. bind

Function.prototype.myBind = function (thisArg, ... args) {
    const self = this
  	const fbound = function () {
    	self.apply(this instanceof self ? this : thisArg,args.concat(Array.prototype.slice.call(arguments)))
  	}
  	fbound.prototype = Object.create(self.prototype)
  	return fbound
}
Copy the code

7, judgment,thisPoint to the

1. obj0.obj.test()

const a = 1
function test () {
    console.log(this.a)
}
const obj = {
    a: 2,
    test
}
const obj0 = {
    a: 3,
    obj 
}
obj0.obj.test() / / 2
Copy the code

2. testcopy()

var a = 1
function test () {
    console.log(this.a)
}
const obj = {
    a: 2,
    test
}
const testCopy = obj.test
testCopy() / / 1
// This reference is determined when the function is executed
Copy the code

In 3.setTimeout

var a = 1
function test () {
    console.log(this.a)
}
const obj = {
    a: 2,
    test
}
setTimeout(obj.test) / / 1
// This reference is determined when the function is executed
Copy the code

Seven,JSmodular

1, modular development history

  • IIFESelf-executing function
  • AMDuserequireJSTo write modularity (dependencies must be declared in advance.)
  • CMDuseseaJSTo write modularity (to support the dynamic introduction of dependency files.
  • CommonJS nodeJsModularity is built in
  • UMDCompatible withAMD,CommonJSgrammar
  • webpack(require.ensure):webpack 2.xCode segmentation in version
  • ES Modules:ES6Introduced modularity, supportimportLet’s introduce another onejs
  • scriptThe labeltype="module"

2,AMDCMDThe difference between

The biggest difference between AMD and CMD is the execution timing of the dependent module. Note that it is not the timing or the way of loading the module. Both load modules asynchronously

  • AMDWhen defining a module, you must declare which module it depends on
  • CMDThe nearest dependencies are recommended, only when a module is neededrequire

3,CommonJSCharacteristics of the specification

  1. So code runs in the module scope and does not contaminate the global scope
  2. Modules are loaded synchronously. The following operations are performed only after the imported modules are loaded
  3. The module is cached after the first execution, and reloading returns only the cached results
  4. CommonJSThe output is a copy of the value, which will not be affected by changes inside the module (reference types are different from basic types).

4,ES6 modulesWhat are the characteristics of the specification

  1. The output usingexport
  2. Introduction to useimport
  3. You can useexport ... from ...To achieve a transit effect
  4. The input module variable is not reassigned. It’s just a readable reference, but the property can be overwritten
  5. exportimportThe command is at the top level of the module, cannot be in scope, is in the code block, cannot do static optimization, violatedES6The design of the module
  6. importIf there is an improvement effect, it will be promoted to the head of the entire module, which is executed first
  7. Babeltheexport/importintoexports/requireSo you can useexportsimport

5,CommonJSES6 ModulesDifferences in specifications

  1. CommonJSModules are loaded at runtime,ES6ModulesIs loaded at compile time
  2. CommonJSCopy of the output value,ES6ModulesReferences to output values (internal module changes affect references)
  3. CommonJSThe import module can be an expression (which is used byrequire()The introduction of),ES6ModulesImports can only be strings
  4. CommonJSWhere this refers to the current module,ES6ModulesthisPoint to theundefined
  5. ES6ModulesThere is noarguments,require,module,exports,__filename,__dirnameThese top-level variables

6. How to load modules asynchronously

AMD and CMD support asynchronous loading modules

7. What issues should be considered when developing a module?

  1. security
  2. closed
  3. Avoid variable conflict
  4. Isolation scope
  5. The withdrawal of common code

Eight,node require(X)What is the processing order introduced?

  1. ifXIf it is a built-in module, this module is returned and the execution is not continued.
  2. ifX'./', '/', '.. / 'The beginning will be based onXParent module, okXThe absolute path of: aXIf the file exists, return the file and do not continue the execution. B. willXIf it is a directory, the system searches for files in the directory one by one. If the file exists, the system returns the file and stops executing the file.
  3. ifXWithout a path: a. According toXParent module, okXPossible installation directories b. In each directory in turn, willXLoad as filename or directory name
  4. thrownot founderror

9. Nodes reference each other

There are two files, a.js and B.JS, which reference each other

1. CommonJS

{
  id: '... '.exports: {... },loaded: true.parent: null.filename: ' '.children: [].paths: []}Copy the code

A CommonJS module is a script file. The first time the require command loads the script, it executes the entire script and then generates an object in memory. If you want to use this module in the future, it will go to the exports attribute. Even if the require command is executed again, the module will not be executed again, but will be stored in the cache.

An important feature of CommonJS is that it is executed at load time and the script code is fully executed at require.

CommonJS prints only the parts that have been executed, not the parts that have not been executed, once a module is “looping loaded.”

// a.js
exports.done = false;
var b = require('./b.js');
console.log('among a.js, B.one = %j', b.done);
exports.done = true;
console.log('A.js completed');
//b.js
exports.done = false;
var a = require('./a.js');
console.log('in b.js, a.do = %j', a.done);
exports.done = true;
console.log('B.js execution completed');
Copy the code
  1. a.jsThe script outputs one firstdoneVariable, and load another script fileb.js. Notice that at this pointa.jsThe code just sits there, waitingb.jsWhen you’re done, let’s move on.
  2. b.jsOn the second line, it will loada.jsAt this point, a “looping load” occurs. The system will go toa.jsModule of the corresponding objectexportsProperty value, but becausea.jsIt’s not done yet, sinceexportsProperties can only fetch the part that has been executed, not the final value.
  3. a.jsThe part that has been executed has only one line.
exports.done = false;
Copy the code
  1. So, forb.jsIn terms of, it comes froma.jsEnter only one variabledoneAnd has a value offalse.
  2. b.jsThen go down the execution, until all the execution is completed, then the execution power back toa.js. As a result,a.jsThen continue to execute, until the execution is complete. Let’s write a scriptmain.js, and run to verify the process.
// main.js
var a = require('./a.js');
var b = require('./b.js');
console.log('in main.js, a.one =%j, B.one =%j', a.done, b.done);
/ / run
// In b.js, a.one = false
// b.js The command is executed
// In a.js, b.one = true
// a.js The command is executed
// In main.js, a.one =true, B.one =true
Copy the code
  1. The above code proves two things. One is inb.js,a.jsIt’s not finished. Only the first line is executed. The second is,main.jsOn the second line, it will not be executed againb.js, but the output cacheb.js, which is the fourth line.

2. ES6

The ES6 module works differently from CommonJS in that it does not execute the module when it encounters the module loading command import, but instead generates a reference. Wait until you really need to use it, then go to the module to the value.

ES6 modules are dynamic references, there is no problem with cached values, and variables in the module are bound to the module in which they are located. The ES6 module does not cache the results of the run, but instead dynamically loads the value of the module, and variables are always bound to the module in which they are loaded.

ES6 doesn’t care if a “loop load” occurs, it just generates a reference to the loaded module, and the developer needs to make sure that the actual value is retrieved.

// even.js
import { odd } from './odd'
export var counter = 0;
export function even(n) {
  counter++;
  return n == 0 || odd(n - 1);
}
// odd.js
import { even } from './even';
export function odd(n) {
  returnn ! =0 && even(n - 1);
}
Copy the code

According to the CommonJS specification, it cannot be loaded and will report an error, but ES6 can execute it. This is possible because ES6 loads variables that refer dynamically to the module in which they are loaded. As long as the reference exists, the code executes.

$ babel-node
> import * as m from './even.js';
> m.even(10);
true
> m.counter
6
> m.even(20)
true
> m.counter
17
Copy the code

In the above code, foo() is executed six times as n goes from 10 to 0, so counter is equal to 6. On the second call to even(), the argument n goes from 20 to 0, and foo() is executed 11 times, plus the previous 6 times, so the variable counter is equal to 17.

Eight,JSThe event

1. What is event delegate

Event delegate/event proxy: Typically, an element’s functions that respond to events are represented on its parent or outer element through event bubbling.

Disadvantages:

  1. Only bubbling events are supported, non-bubbling events cannot be brokered (focus/blur )
  2. All events are agent prone to error, recommend nearby delegate
  3. Internal element hierarchy is too many, easy to be blocked by a layer

2,document,window,html,bodyThe hierarchy of

window > document > html > body

  • windowBOMOn the one hand, the core object is used to get or set the browser properties and behavior, on the other hand, as a global object;
  • documentIs a document-related object that has some ability to manipulate the contents of the document;
  • htmlElements anddocumentElement objects belong tohtmlThe documentDOMObject.

3,addEventListenerWhat’s the third argument to the function?

1. When tobooleanWhen:

  • The third parameter involves whether to bubble or capture;
    • fortrueWhere is capture, isfalseIt is bubbling.

2. When toObjectWhen:

  • capture:BooleanSaid,listenerIs propagated to this during the event capture phase of this typeEventTargetWhen triggered.
  • once:BooleanSaid,listenerIt is called at most once after adding. If it istrue.listenerWill be removed automatically after it is called.
  • passive:Boolean, is set totrueSaid,listenerNever callpreventDefault(). iflistenerIf the function is still called, the client will ignore it and throw a console warning.
  • mozSystemGroup: only inXBLOr is itFirefox' chromeUse, this is aBooleanSaid,listenerIs added to thesystem group.

4. The specific process of bubble and capture

Bubble: When an event is bound to an element, the event is fired in turn on its parent element; Capture: Transfer from top to bottom, as opposed to bubbling.

<! Button li ul -->
<ul onclick="alert('ul')">
  <li onclick="alert('li')">
    <button onclick="alert('button')">Click on the</button>
  </li>
</ul>
<script>
  window.addEventListener('click'.function (e) {
    alert('window')})document.addEventListener('click'.function (e) {
    alert('document')})</script>
Copy the code

Button -> li -> ul -> document -> window -> document -> ul -> li -> button

5. What are the non-bubbling events

  • onblur
  • onfoucs
  • onmouseenter
  • onmouseleave

6. Native custom events

1. What user-defined events are available

  • useEvent
  • usecustomEvent
  • usedocument.createEvent('customEventName')initEvent()

2. Create a custom event

1) useEvent
let myEvent = new Event('my_event_name')
Copy the code
2) usecustomEvent
let myEvent = new CustomEvent('my_event_name', {
    detail: {
    // The parameters to be passed
    // Get: event.detail in the listener callback function}})Copy the code
3) usedocument.createEvent('CustomEvent')initEvent()
let myEvent = document.createEvent('CustomEvent')
myEvent.initEvent(
    Event_name is the event name
  // canBubble whether to bubble
  Cancelable Whether the default behavior can be cancelled
)
Copy the code

3. Event monitoring

dom.addEventListener('my_custom_name'.function(e) {})
Copy the code

4. The event is triggered

dispatchEvent(myEvent)
Copy the code

Case 5.

/ / 1.
let myEvent = new Event('myEvent');
/ / 2.
let myEvent = new CustomEvent('myEvent', {
  detail: {
    name: 'lindaidai'}})/ / 3.
let myEvent = document.createEvent('CustomEvent');
myEvent.initEvent('myEvent'.true.true)
let btn = document.getElementsByTagName('button') [0]
btn.addEventListener('myEvent'.function (e) {
  console.log(e)
  console.log(e.detail)
})
setTimeout(() = > {
  btn.dispatchEvent(myEvent)
}, 2000)
Copy the code

Nine,JSInternal functions and closures

1. What are closures

MDN: A function is bound with a reference to its surrounding state (lexical environment). Such a combination is a closure.

To put it simply: a function that can read variables inside another function is a closure.

for (var i = 0; i < 10; i++) {
  (function (i) {
    setTimeout(() = > {
      console.log(i)
    }, 1000)
  })(i)
}
Copy the code

2. What is an internal function

In general, a function defined inside another function is an internal function.

3. What do closures do?

  1. Using closures, you can access variables in a function;
  2. Variables can be kept in memory for a long time.

4. Memory leak

1. Memory leak:

  1. A circular reference
  2. Automatic boxing conversion
  3. Some of theDOMoperation

(44. Closure

2. Memory leak solution:

  1. Below cast, which can be avoided by displaying cast;
  2. Avoid circular references caused by events;
  3. Dustbin operation;
  4. Manual deletion of variables;

3. Memory leak is the memory footprint very large?

No, even 1byte of memory is called a memory leak.

4. The program prompts that memory is insufficient. Is it a memory leak?

No, it is usually an infinite recursive function call, resulting in stack memory overflow.

5. Which region is the memory leak?

The heap area. Stacks do not leak

6. What are the consequences of memory leaks?

In most cases, the consequences are not very serious. But too much DOM manipulation can slow down web page execution.

7. Jump to the web page, does the memory leak still exist?

Still exists until the browser closes.

Ten,EventLoopExecution process of

1. BrieflyEventLoopExecution process of

  • The wholescriptExecute as a macro task;
  • In execution, the synchronous code is executed directly, the macro task enters the macro task queue, and the micro task enters the micro task queue;
  • After the execution of the current macro task is completed, the microtask list is detected. If there is a microtask, the microtask is executed until all the microtask list is executed.
  • Perform the browser’sUIThread rendering work;
  • Check whether there isweb workerTask, have to perform;
  • When this round of macro tasks is completed, go back to step 2 and loop until both the macro and microtask queues are empty.

2,requestAnimationFrame

Characteristics of 1.

  1. Called before rerendering.
  2. Most likely not called after the macro task.

2. Why is it called before rerendering?

RAF is the officially recommended API for some smooth animations, and it is inevitable to change the DOM when making animations, and if you change the DOM after rendering, you can only draw it when the next rendering opportunity comes, which is obviously unreasonable.

RAF gives you one last chance to change the DOM properties before the browser decides to render them, and then renders them for you quickly in the following drawing, so this is the perfect choice for smooth animation.

3,requestIdleCallback

The requestIdleCallback method queues functions that are called during idle periods in the browser. This enables developers to perform background and low-priority work on the main event loop without affecting the delay of critical events such as animations and input responses.

1. Render in order

2. Render idle for a long time

50msIt ensures that the user gets a response with an unconscious delay.

4,EventLoopCirculatory Points

  • The event loop does not have to be accompanied by a heavy render every round, but if there is a microtask, it must be accompanied by a microtask execution.
  • There are many factors that determine whether a browser view is rendered or not, and browsers are very smart.
  • requestAnimationFrameExecuted before re-rendering the screen, which is great for animating.
  • requestIdleCallbackExecute after rendering the screen, and whether or not you have time to execute depends on the browser’s schedule. If you must have it execute at a certain time, please use ittimeoutParameters.
  • resizescrollThe event actually has its own throttling, it only inEvent LoopThe render phase to dispatch events toEventTargetOn.

5,forCirculation andsetTimeout

Add a setTimeout to the for loop

for (var i = 0; i < 10; i++) {
     setTimeout(() = > {
       console.log(i)
     }, 1000)}Copy the code

1. vartolet

for (let i = 0; i < 10; i++) {
  setTimeout(() = > {
    console.log(i)
  }, 1000)}Copy the code

2. Use self-executing functions

for (var i = 0; i < 10; i++) {
  (function (i) {
    setTimeout(() = > {
      console.log(i)
    }, 1000)
  })(i)
}
Copy the code

3. forLoop toforEachcycle

[1.2.3.4].forEach(item= > {
  setTimeout(() = > {
    console.log(item)
  }, 1000)})Copy the code

4. setTimeoutThe ginseng

for (var i = 0; i < arr.length; i++) {
  setTimeout((i) = > {
    console.log(arr[i])
  }, 1000, i)
}
Copy the code

5. Direct output

for (var i = 0; i< 10; i++){
  setTimeout(console.log(i),1000);
}
Copy the code

Eleven,JSIn thelet,const,var

1.JSHow many ways are there to define variables in

  • let
  • const
  • var
  • class
  • import
  • function

2,let,const,varWhat’s the difference?

var let const
There is no block-level scope There is block-level scope There is block-level scope
Declare global variables inwindow (under global attribute) Global variables are not under global attribute Global variables are not under global properties
No error is reported when redefining a variable complains complains
Declare a variable Declare a variable Declare a constant
Improvement of existing variables There is no variable promotion There is no variable promotion
Assign at any time after declaration Assign at any time after declaration Assign immediately after declaration

3,constCan defined constants be modified?

  1. constDefined base types are not modifiable;
  2. constDefining a reference type allows you to modify the value within the reference type.

4. If I want toconstWhat if defining a reference type doesn’t change its value?

  1. Object.freeze;
  2. Agent (proxy/Object.defineProperty);
  3. Modify an object’sconfigurable,writableProperties.

5, how to inES5Is implemented in the case ofletconst?

1. The implementationlet

This can be done through self-executing functions.

2. Implementconst

You can set writable via object.defineProperty ().

Twelve,JSAn array of

1.ES6New array method

Array.from(), array.of (), copyWithin(), find(), findIndex(), fill(), entries(), keys(), values(), includes().

2,ES5New array method

ForEach (), map(), filter(), some(), every(), indexOf(), lastIndexOf(), Reduce (), reduceRight().

3. Which of these methods can change the original array?

CopyWithin (), fill(), pop(), push(), reverse(), shift(), sort(), splice().

4,someeveryWhat’s the difference?

“Some” means “some”, “every” means “every”, and they all return a Boolean value.

5, there are 100,000 data in the array, take the first element or the 100,000th element which use time?

The Times are basically the same, because js doesn’t have an array type, and an array is actually an object, key and value.

6. How many methods do you have for rearranging arrays?

1. Multilayer loop traversal

  • doubleforCycle;
  • Recursive loop.

2. Use the syntax itself with keys that are not repeatable or API repeatable

  • ES6 SetGo to the heavy;
  • Create an empty object to deduplicate;
  • Single layer circulation +filter/includes/indexOf;
  • Single layer circulation +Map,Objectduplicate removal

7,forCirculation andforEachWhich performance is better?

forLoops perform better

  • forLoop without any additional function call stack and context;
  • forEachNot ordinaryforThe syntax sugar of the loop, as well as the many parameters and context that need to be taken into account during execution, can drag on.

Eight,sortWhat kind of sorting is done?

The default sort order is built when you convert elements to strings and then compare them to a sequence of UTF-16 code unit values.

9. Turn a multidimensional array into a one-dimensional array

  • reduceThe recursive implementation
  • joinsplitimplementation
  • The recursive traversal
  • flatmethods
  • toStringsplitimplementation
  • Breadth first traversal/depth first traversal

How to implement breadth-first traversal and depth-first traversal

Depth first traversal and breadth first traversal

1. Depth-first traversal

  • Access to the verticesv;
  • In turn, fromvThe depth first traversal of the graph is carried out. Until the figure neutralizesvAll vertices that have paths are accessed;
  • If there are still vertices not visited, the depth-first walk starts from an unvisited vertex and continues until all vertices have been visited.
const depth = (node) = > {
    let stack = []
    let nodes = []
    if (node) {
        stack.push(node)
        while (stack.length) {
            // Take the last one at a time
            let item = stack.pop()
            let children = item.children || []
            nodes.push(item)
            // Judge the length of children
            for (let i = children.length - 1; i >= 0; i--) {
                stack.push(children[i])
            }
        }
    }
    return nodes
}
Copy the code

2. Breadth first traversal

  • Create a queue and put the start node into the queue.
  • If the queue is not empty, the first node is taken out of the queue and it is checked whether it is the target node.
  • If it is the target node, the search ends and the result is returned.
  • If not, all its undetected byte points are added to the queue;
  • If the queue is empty, there is no target node in the graph, and the traversal ends.
const breadth = (node) = > {
    let nodes = []
    let stack = []
    if (node) {
        stack.push(node)
        while (stack.length) {
            // Take the first one
            let item = stack.shift()
            let children = item.children || []
            nodes.push(item)
            for (let i = 0; i < children.length; i++) {
                stack.push(children[i])
            }
        }
    }
    return nodes
}
Copy the code

Implement onereduce

Array.prototype.myReduce = function (fn, init) {
    if(! init &&this.length === 0) { // If the array length is 0
        return this
    }
    let start = 1, pre = this[0]; // Start from the second array with subscript 1
    if(init ! = =undefined) { // If init field exists, start with the first one, subscript 0
        start = 0;
        pre = init;
    }
    for (let i = start; i < this.length; i++) { / / loop
        let current = this[i]
        pre = fn.call(this, pre, current, i, this) // Return each reduce value
    }
    return pre
}
Copy the code

Implement an array random shuffling algorithm

function disOrder2 (arr) {
    for (let i = 0; i < arr.length; i++) { / / traverse
        const randomIndex = Math.floor(Math.random() * ary.length) // Generate random numbers
        swap(arr, i, randomIndex)
    }
}
function swap(arr, i, _i) { / / exchange
    const tem = arr[i]
    arr[i] = arr[_i]
    arr[_i] = tem  
}
arr = [1.2.3.4.5.6.7.8]
disOrder(arr)
console.log(arr)
Copy the code

Add a comma to a string of numbers

1. Regular

num.replace(/(\d)(? =(\d{3})+(\.|$))/g."$1")
Copy the code

2. Traversal

function formatNumber(num) {
  if(! num)return "";
  let [int, float] = num.split(".");
  let intArr = int.split("");
  let result = [];
  let i = 0;
  while (intArr.length) {
    if(i ! = =0 && i % 3= = =0) {
      result.unshift(intArr.pop() + ",");
    } else {
      result.unshift(intArr.pop());
    }
    i++;
  }
  return result.join("") + "." + (float ? float : "");
}
Copy the code

14,map,find,every,some,forEachWhat is the second parameter of the etc method?

arr.every(callback(element[, index[, array]])[, thisArg])
Copy the code
  • thisArg

The value of this used when executing the callback.

Thirteen,for infor ofWhat’s the difference?

To compare for in for of
The difference between You can iterate over normal objects

Iterates through the prototype object of the array

You can iterate through the array itself

The value that I’m going to iterate over is 0key

It is not traversablemap/set

You can’t iterategenerators

Internet explorer support
Normal objects cannot be traversed

It doesn’t iterate through the prototype object

It doesn’t iterate over its own properties

The value that I’m going to iterate over is 0value

Can traversemap/set

To iterategenerators

IE does not support
The same You can iterate through groups of numbers

canbreakInterrupt traversal
You can iterate through groups of numbers

canbreakInterrupt traversal

Fourteen,Promise

1. How to implement onesleepFunction (delay function)

Simple implementation with promise and setTimeout

/** * delay function *@param {Number} Time time * /
function sleep (time = 1500) {
    return new Promise((resolve) = > {
        setTimeout(() = > {
            resolve(true)
        }, time)
    })
}
Copy the code

2,promiseConstructor,thenMethods,catchMethods,finallyWhich method is asynchronous and which method is synchronous?

The PROMISE constructor executes synchronously, and the THEN, catch, and finally methods execute asynchronously.

3. How to cancel onepromise?

Cancel a promise

1. Usepromise.race()

  • Promise.race(iterable)

When any child promise in iterable succeeds or fails, the parent promise immediately calls the corresponding handle of the parent promise binding with the success or failure details of the child promise, and returns the promise object.

/ * * *@author guoqiankunmiss* /
// Encapsulate a function to cancel a promise, using the promise.race feature
function stopPromise (stopP) {
	let proObj = {};
	let promise = new Promise((resolve, reject) = > {
		proObj.resolve = resolve;
		proObj.reject = reject;
	})
	proObj.promise = Promise.race([stopP, promise])
	return proObj
}
// A promise for the.then method executed 5 seconds later
let promise = new Promise((resolve, reject) = > {
    setTimeout(() = > {
        resolve(123);
    }, 5000);
});
// Call the function
let obj = stopPromise(promise);
// Collect the return value
obj.promise.then(res= > {
    console.log(res);
});
// Cancel the promise after two seconds
setTimeout(() = > {
	obj.resolve("Promise request canceled!");
}, 2000)
Copy the code

More than 4,promiseHow do you achieve your first successpromise?

Get the first successful Promise out of multiple promises

1. Promise.allTo improve the

Use the promise. All feature to iterate through the promise array and determine the return value. When the promise array succeeds, it is rejected and when the promise array fails, it is resolved.

// The first successful Promise
function firstProSuccess (allProMise) {
  // Iterate over the promise array and determine the return value. Reject on success and resolve on failure.
  return Promise.all(allProMise.map(item= > {
    return item.then(
      res= > Promise.reject(res),
      err= > Promise.resolve(err)
    )
  })).then(
    errors= > Promise.reject(errors),
    val= > Promise.resolve(val)
  )
}
Copy the code

2. Promise.any

  • Promise.any(iterable)

Receives a collection of Promise objects and returns the value of that successful Promise when one of the promises succeeds.

Cons: Compatibility issues

More than 5,promiseAnd all thepromiseReturns the result regardless of success/failure.

1. Promise.allTo improve the

The principle is similar to the above, except that when successful, the action is not done, and when reject, the action is resolved

2. Promise.allSettled()

  • Promise.allSettled(iterable)

This will be fulfilled someday. Return a promise that has been fulfilled after all the given promises have been fulfilled.

Cons: Compatibility issues

6, tell me aboutpromiseWhat are the static methods of?

1. Promise.all(iterable)

Receive a promise array object (an iterable Promise instance object) and return an array collection of all promises when all are successful. When one of them fails, the currently failing PROMISE object is returned.

2. Promise.allSettled(iterable)

Receive a promise array object and return a new collection of Promise arrays when all are completed (regardless of success/failure)

3. Promise.any(iterable)

Receives a promise array object and returns a promise value when any of them is successful

4. Promise.race(iterable)

Receives a promise array object and returns the promise value if any of them succeeds/fails

5. Promise.reject(reason)

Return a Promise object with the failed state.

6. Promise.resolve(value)

Returns a Promise object whose state is determined by the given value.

7. Promise.finally(onFinally)

This promise will be called once it has finished running, whether it is fulfilled or failed.

8. Promise.try(f)

Receive a function and return a promise.

It provides a unified processing mechanism for all operations, so if you want to manage the process with the THEN method, it is best to wrap it all in promise.try.

  • Better error handling
  • Better interoperability
  • Easy to navigate

Promise-try

7,Promise.thenDo you know the second parameter of? and.catchWhat’s the difference?

The then() method returns a Promise.

It takes up to two arguments: the Promise’s success and failure case callbacks.

p.then(onFulfilled[, onRejected]);
p.then(value= > {
  // fulfillment
}, reason= > {
  // rejection
});
Copy the code

The second argument is also a function, a callback for failure.

thenSecond parameter catch
thenMethod parameters PromiseInstance method of
thenThe first argument to the exception that is thrown cannot be caught The first argument to then throws an exception that can be caught
It’s a function Nature isthenMethod syntax sugar
If the second argument is the sumcatchCo-existence,promiseInternal error, second parameter can be captured At this point,catchNo, the second parameter does not exist,catchTo capture
Not recommended It is recommended to usecatchError catching

Eight,Promise.resolveHow many cases?

1. Parameter is onePromiseThe instance

If the argument is a Promise instance, promise.resolve will return the instance intact, with no modifications.

2. Parameter is onethenableobject

The promise.resolve () method converts this object to a Promise object, and then executes the then() method of the thenable object immediately.

3. The parameter is not availablethen()Method object, or not an object at all

If the argument is a raw value, or an object that does not have a then() method, the promise.resolve () method returns a new Promise object in the resolved state.

4. No parameters

Return a Promise object in the Resolved state.

9, if.thenIs not a function?

Promise.resolve(1)
    .then(2)
    .then(console.log)
/ / 1
Copy the code

If the argument in.then is not a function, it is internally replaced with (x) => x, which returns the promise as it is.

10, if.finallyFollowed by a.then, so thisthenWhat are the values inside?

Promise.resolve('resolve')
  .finally(() = > {
    console.log('this is finally')
    return 'finally value'
  })
  .then(res= > {
    console.log('then function after finally, res value:', res)
  })
// this is finally
Copy the code

The then function after finally, res has the value: resolve

  1. finallyTakes no arguments in the callback function of;
  2. inpromiseAt the end, whatever the result isfulfilledOr is itrejected, will be implementedfinallyCallback function;
  3. finallyIt returns a previous onePromiseObject value.

11,.all.raceDo other asynchronous tasks continue to execute when the first exception is thrown in the passed array?

Yes, it will continue to execute, but it will not show up in the then/catch.

When the browser executes the following code, you can see that the console continues to execute when an error is reported, but there is no indication in the corresponding callback function.

function sleep (n) {
    return new Promise((resolve, reject) = > {
        console.log(n)
        Math.random() > 0.5 ? reject(n) : resolve(n)
    }, n % 2= = =0 ? 1000 * n : 1000)}Promise.all([sleep(1), sleep(2), sleep(3)])
  .then(res= > console.log('all res: ', res))
  .catch(err= > console.log('all err:', err))
Promise.race([sleep(1), sleep(2), sleep(3)])
  .then(res= > console.log('race res: ', res))
  .catch(err= > console.log('race err:', err))
Copy the code

12,.allIs it concurrent or serial?

Is concurrent, but the return value is in the same order as the array received in promise.all.

13,promiseWhy is it possible to chain calls

Because the THEN, catch, and finally methods return a new promise, we are allowed to chain calls.

14,async/await

1. Implementation principle

The async function is implemented based on generator, so it involves the knowledge of generator. Before async functions were available, it was common to use the CO library to execute the generator, so with CO we can also simulate the implementation of async.

2. Simple implementation

1)co
function Asyncfn() {
  return co(function* () {
    / /...
  });
}
function co(gen) {
  return new Promise((resolve, reject) = > {
    const fn = gen();
    function next(data) {
      let { value, done } = fn.next(data);
      if (done) return resolve(value);
      Promise.resolve(value).then(res= > {
        next(res);
      }, reject);
    }
    next();
  });
}
Copy the code
2)GeneratorFunctions and self-effectors
function spawn(genF) {
    return new Promise(function(resolve, reject) {
        const gen = genF();
        function step(nextF) {
            let next;
            try {
                next = nextF();
            } catch (e) {
                return reject(e);
            }
            if (next.done) {
                return resolve(next.value);
            }
            Promise.resolve(next.value).then(
                function(v) {
                    step(function() {
                        return gen.next(v);
                    });
                },
                function(e) {
                    step(function() {
                        returngen.throw(e); }); }); } step(function() {
            return gen.next(undefined);
        });
    });
}
Copy the code

Fifteen, sayJSON.stringifyJSON.parse

1.JSON.stringify

Definition: Converts a JavaScript object or value to a JSON string. Parameters: There are three parameters

JSON.stringify(value[, replacer [, space]])
Copy the code
  1. replacer

The replacer argument can be a function or an array. As a function, it takes two arguments, a key and a value, both of which are serialized. The replacer is an array whose values represent the names of the properties to be serialized into a JSON string. 2. Space The space parameter controls the spacing in the result string. If it is a number, each level will indent more space in the value of that number than the previous level during stringification; If it is a string, each level indents the string more than the previous level.

2,JSON.parse

Definition: Used to parse JSON strings. Parameters: There are two parameters

JSON.parse(text[, reviver])
Copy the code
  1. reviver

The converter, if passed, can be used to modify the original value generated by the parse.

features

  1. Convert value if there istoJSON()Method that defines what values will be serialized.
  2. Properties of non-array objects are not guaranteed to appear in a serialized string in a particular order.
  3. Boolean, numeric, and string wrapper objects are automatically converted to their original values during serialization.
  4. undefined, any function andsymbolValue, which is either ignored during serialization (when the property value of a non-array object is present) or converted tonull(when appearing in an array). The function,undefinedWhen converted individually, returnsundefined, such asJSON.stringify(function(){}) or JSON.stringify(undefined).
  5. Executing this method on objects that contain circular references (objects that refer to each other in an infinite loop) throws an error.
  6. All tosymbolProperties that are property keys are completely ignored, even if they are included in the replacer parameter.
  7. DateThe date is calledtoJSON()Convert it tostringString (same asDate.toISOString()), so it is treated as a string.
  8. NaNInfinityFormat andnullWill be treated asnull.
  9. Other types of objects includeMap/Set/WeakMap/WeakSet, serializes only enumerable properties.

16,= =,= = =Object.is()

1, the difference between

  • = =If the two values are of different types, they are first cast and then compared
  • = = =Direct value comparison without type conversion
  • Object.is(val1, val2)Determine whether the two values are the same

2,= =How is a type conversion done?

  1. If the type is different, the conversion is performed
  2. Determine whether the comparison isnullOr is itundefinedIf yes, returntrue
  3. Check whether the type isstringornumber, if so, willstringconvertnumber
  4. Determine whether one of the parties isbooleanIf yes, convert one party to the othernumberIn judgment
  5. Determine whether one of the parties isobjectAnd the other side isstring,number,symbol, if so, willobjectConvert to primitive type for judgment (valueOf()Methods)
  6. If one of them isNaNIs returned directlyfalse
  7. If both are objects, the comparison points to the same object

3,[] = =! []What is the value of?

Answer: true

The transformation steps

  1. ! Operator has the highest priority,! []Will be converted tofalse, therefore, is[] == false
  2. According to article 4, one of the parties isboolean,booleantonumber, so this is[] = = 0
  3. And then according to article 5, the array[]Convert to the original type and call the arraytoString()Method,[].toString() = '', so this is' '= = 0
  4. And then according to the third rule, putstringtonumber.' 'tonumberTheta is zero. So at this point0 = = 0
  5. The data types on both sides are the same0 = = 0fortrue

4, object.is () determines if two values are equal

Casts are not performed

  • Are allundefined
  • Are allnull
  • Are alltruefalse
  • Are all strings of the same length and the same characters in the same order
  • Are all the same object (meaning each object has the same reference)
  • It’s all numbers and
    • Are all+ 0
    • Are all0
    • Are allNaN
    • Or both are nonzero and nonzeroNaNAnd be the same value

17, shake and throttling

1. What are shockproof and throttling

Throttling: Throttling: Throttling: throttling: throttling: throttling: throttling: throttling: throttling

2. Simple stabilization and throttling

1. Shockproof realization

The function executes only once for n seconds after the event is triggered. If the event is triggered again within n seconds, the time is recalculated and the delay is cancelled each time the event is triggered

function debounce (fn, time = 500) {
  let timeout = null; // Create a tag to hold the return value of the timer
  return function () {
    clearTimeout(timeout) // On each trigger, clear the previous timer
    timeout = setTimeout(() = > { // Create a new timer and assign it to timeout
      fn.apply(this.arguments)
    }, time)
  }
}
function testDebounce () {
  console.log('Test anti-shaking')}const inp = document.getElementById('testInp')
inp.addEventListener('input', debounce(testDebounce))
Copy the code

2. Throttling implementation

High frequency events are triggered, but only once in n seconds, so throttling dilutes the frequency of function execution, and each time the event is triggered it determines whether there is a delay function waiting to be executed

function throttle (fn, time = 100) {
  let timeout;
  return function () {
    let context = this
    let args = arguments
    if(! timeout) { timeout =setTimeout(() = > {
        timeout = null
        fn.apply(context, args)
      }, time)
    }
  }
}
function testThro () {
  console.log('Test throttling')}const inp = document.getElementById('testInp')
inp.addEventListener('input', throttle(testThro))
Copy the code

Eighteen,cookie,sessionStoragelocalStorage

1, the difference between the three

  • cookieUsed to save login information. The size limit is4KBOr so
  • localStorageHtml5Newly added, used for local data storage, saved data has no expiration time, general browser size is limited to5MB
  • sessionStorageInterface methods andlocalStorageSimilar, but the saved data is saved only for the current session and is cleared when the page closes.
The name of the Life span Size limit Communicating with the server Whether to cross domains
cookie Usually generated by the server, you can set the expiration time. If you generate it in the browserCookie, the default value is invalid after the browser is closed 4KB Every timeHTTPHeader, if usedcookieSaving too much data can cause performance problems Generally not, the samedomainCan allow interface request to carrycookie
localStorage Stored permanently unless cleared 5MB Only saved in the browser, does not communicate with the server Do not
sessionStorage This parameter is valid only for the current session and is cleared when the page or browser is closed 5MB Only saved in the browser, does not communicate with the server Do not

2,localStorageHow to perform cross-domain storage?

LocalStorage is not allowed to perform cross-domain operations, but want to cross-domain operations can use postMessage, Websocket disguised cross-domain operations.

Browser cross-domain problem

1. What is the browser same origin policy?

The same origin policy is an important security policy that restricts how an Origin document or the script it loads can interact with the resources of another source. It can help block malicious documents and reduce the media that may be attacked.

The same origin policy refers to the same origin policy only in the address:

  1. Agreement,
  2. The domain name
  3. The port name

You can access the same cookie, localStorage, and access the DOM of the page or send Ajax requests only if they are the same.

2. What are the dangerous scenarios without same-origin policy restrictions?

  • ajxarequest
  • DomThe query

Same origin policy does avoid some dangers, not to say that the same origin policy is safe, but it is one of the most basic browser security mechanism, after all, can increase the attack cost a little bit.

3. Why does the browser forbid cross-domain?

  • Cross-domain only exists on the browser side, because the browser is very open and needs to be limited.
  • The same origin policy is used to protect user information security and prevent malicious data theft (ajaxSame-origin policy,DomSame-origin policy).

4. What are the cross-domain solutions?

CSDN cross-domain problem solved

  1. jsonp
  2. cors
  3. postMessage
  4. websocket
  5. NodeMiddleware broker (twice across domains)
  6. nginxThe reverse proxy
  7. window.name + iframe
  8. location.hash + iframe
  9. document.domain + iframe

5,CORSWhat are the common configurations?

  • Access-Control-Allow-OriginAllowed domain names
  • Access-Control-Allow-MethodsAllow thehttpRequest method
  • Access-Control-Allow-HeadersSupported request headers
  • Access-Control-Allow-CredentialsWhether to sendcookie
  • Access-Control-Max-AgeCache time in seconds

6,CORSCross-domain decision flow

  1. If yes, the browser sends data directly. Otherwise, the browser sends a cross-domain request.
  2. After receiving the cross-domain request, the server returns the corresponding file header according to its configuration.
  3. The browser receives a response based on the headerAccess-Control-Allow-originField. If no field is displayed, cross-domain information is not allowed and an error is reported. If yes, check whether cross-domain information is allowed.

7. What is a simple request?

A simple request is one that satisfies the following conditions:

  • useget,post,headOne of the methods to make the request;
  • httpHeader information for the following:
    • Accept
    • Accept-Language
    • Content-Language
    • Last-Event-ID

Content-type: The value is limited to Application/X-www-form-urlencoded, multipart/form-data, text/plain

  • In the requestXMLHttpRequestUploadThe object does not register any event listeners;
  • XMLHttpRequestUploadObject can be usedXMLHttpRequest.uploadProperty access. Not used in the requestReadableStreamObject.

8. Non-simple requests

Requests that have specific requirements for the server (other than simple requests, non-simple requests).

For example, the request mode is PUT or delete, and the content-type Type is Application/JSON.

A non-simple request initiates a precheck request using Options before formal communication, asking the server if the current domain name is on the server’s allowed list, which header fields to use, and so on.

9. What are the ways to embed cross-source resources?

  • scriptTags, embedded cross-domain scripts;
  • linkTag, embedcss;
  • imgTag, embedded image;
  • video/audioTag, embedded video, audio;
  • object/embed/appletTag, embedsvg/ pictures, etc.;
  • svgTag, embedsvg;
  • through@font-faceEmbedded fonts;
  • throughiframeEmbedded resources

10. Implement one manuallyJSONP

/ / Promise encapsulation
function jsonp({ url, params, callback }) {
  return new Promise((resolve, reject) = > {
    // Create a script tag
    let script = document.createElement('script')
    // Mount callback on window and delete script after execution
    window[callback] = function(data) {
      resolve(data)
      document.body.removeChild(script)
    }
    // Add parametersparams = { ... params, callback }// wd=b&callback=callFun
    let arrs = []
    for (let key in params) {
      arrs.push(`${key}=${params[key]}`)}// Set the URL of script
    script.src = `${url}?${arrs.join('&')}`
    // Insert body
    document.body.appendChild(script)
  })
}
// Call the example
jsonp({
  url: 'http://localhost:3000/code'.params: { wd: 'hello world' },
  callback: 'callFun'
}).then(data= > {
  console.log(data) / / hello
  // Delete the script after the callback
})
Copy the code

Twenty, sayjsInheritance of

JS common six inheritance methods

1. Prototype chain inheritanceprototype

The prototype of a child type is an instance object of the parent type.

Child.prototype = new Parent()
Copy the code

Advantages:

  1. Simple inheritance
  2. The parent class adds new methods, attributes, subclass can access

Disadvantages:

  1. Multiple inheritance is not possible
  2. All properties from the parent class are shared by all instances
  3. To add properties and methods to a subclass, you must add them after child.prototype = new Parent() because they will be overridden
  4. When you create a child class, you cannot pass arguments to the parent class

2. Constructor inheritancecall

The generic call() in the subtype constructor calls the parent type constructor

function Child(name, age, price) {
    Parent.call(this, name, age)  // Equivalent: this.parent (name, age)
}
Copy the code

Advantages:

  1. The problem of subclass instances sharing parent class reference properties in prototype chain inheritance
  2. When you create a subclass instance, you can pass arguments to the parent class
  3. Can implement multiple inheritance (call multiple parent objects)

Disadvantages:

  1. An instance is not an instance of a parent class, just an instance of a child class
  2. Only instance properties and methods of the parent class can be inherited, not prototype properties and methods
  3. Function reuse is not possible, and each subclass has a copy of the parent instance’s function, affecting performance

3, prototype chain + constructor combination inheritanceprototype + call

Call the superclass construct, inherit the properties of the superclass and retain the benefits of passing parameters, and then reuse the function by using the superclass instance as a prototype for the subclass.

function Child (name, age, price) {
  Parent.call(this, name, age)
}
Child.prototype = new Parent()
Child.prototype.constructor = Child// Composite inheritance is also what the constructor points to
Copy the code

Advantages:

  1. You can inherit instance properties/methods as well as stereotype properties/methods
  2. There is no problem with reference attribute sharing
  3. Can pass the cords

Disadvantages:

  1. The superclass constructor is called twice, generating two copies of the instance

4. Combination inheritance optimization 1

With the parent and subclass prototypes pointing to the same object, a subclass can inherit the public methods of the parent class as its own public methods without initializing the instance methods/properties twice, avoiding the disadvantages of combination inheritance.

function Child (name, age, price) {
    Parent.call(this, name, age)
}
Child.prototype = Parent.prototype
Copy the code

Advantages:

  1. The superclass constructor is not called twice

Disadvantages:

  1. There is no way to tell whether the instance is created by the subclass or the superclass. The constructors of the subclass and the superclass point to the same thing.

5. Combinatorial inheritance optimization 2

Var B = object.create (A); var B = object.create (A); B inherits all the properties and methods of A.

function Child (name, age, price) {
    Parent.call(this, name, age)
}
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
Copy the code

6,es6 classThe inheritance of

The class keyword is just syntax sugar for the stereotype, and JavaScript inheritance is still implemented based on the stereotype.

class Parent {
    constructor(name, age) {
        this.name = name
        this.age = age
    }
    setName () {
        console.log('parent')}}let child1 = new Parent('name1'.18)
let child2 = new Parent('name2'.16)
class Child extends Parent {
    constructor(name, age, price) {
        super(name, age)
        this.price = price
    }
    setAge () {
        console.log('Subclass method')}}let child3 = new Child('name3'.20.15000)
let child4 = new Child('name4'.21.10000)
Copy the code

Advantages:

  1. Simple inheritance

21. Sorting algorithm

1. Bubble sort

In simple terms, compare two adjacent elements and replace them in the order you want (ascending or descending), using an extra variable as the intermediate variable to store the value.

function bubbleSort(arr) {
    var len = arr.length;
    for (var i = 0; i < len; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j+1]) {        // Compare adjacent elements in pairs
                var temp = arr[j+1];        // Element exchange
                arr[j+1] = arr[j]; arr[j] = temp; }}}return arr;
}
Copy the code

2. Quicksort

Select a datum and place the smaller one on the left and the smaller one on the right (the datum is in the middle)

function quickSort(arr) {
    // If the array <=1, return it directly
    if (arr.length <= 1) { return arr; }
    var pivotIndex = Math.floor(arr.length / 2);
    // Find the datum and delete it from the original array
    var pivot = arr.splice(pivotIndex, 1) [0];
    // Define left and right arrays
    var left = [];
    var right = [];
    // Put the smaller ones on the left and the larger ones on the right
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] <= pivot) {
            left.push(arr[i]);
        }
        else{ right.push(arr[i]); }}/ / recursion
    return quickSort(left).concat([pivot], quickSort(right));
}
Copy the code

3. Select sort

First find the smallest element in the original array and put that element first. Then find the smallest element in the remaining elements and put it after the previous smallest element until the sorting is complete

function selectionSort(arr) {
    var len = arr.length;
    var minIndex, temp;
    for (var i = 0; i < len - 1; i++) {
      minIndex = i;
      for (var j = i + 1; j < len; j++) {
        if (arr[j] < arr[minIndex]) {
          minIndex = j;
        }
      }
      temp = arr[i];
      arr[i] = arr[minIndex];
      arr[minIndex] = temp;
    }
    return arr;
}
Copy the code

4. Insertion sort

Starting from the second element (assuming the first element has been sorting), remove the element, in already sorted elements from forward after the comparison, if the element is greater than the element, just move the element to the next place, and then move on, until you find less than or equal to the element’s position, insert the element to this location. Repeat this step until the sorting is complete

function insertionSort(arr) {
  var len = arr.length;
  var preIndex, current;
  for (var i = 1; i < len; i++) {
    preIndex = i - 1;
    current = arr[i];
    while (preIndex >= 0 && arr[preIndex] > current) {
      arr[preIndex + 1] = arr[preIndex];
      preIndex--;
    }
    arr[preIndex + 1] = current;
  }
  return arr;
}
Copy the code

Merge sort

Merge sort is an efficient sorting algorithm based on merge operation. The algorithm is based on the divide-and-conquer (Divide and Conquer) is a very typical application. Merge sort is a stable sort method. The ordered subsequence is merged to obtain a completely ordered sequence. That is, to order each subsequence, and then to order the subsequence segments. If two ordered tables are merged into one, it is called 2-way merge.

function mergeSort(arr) {  // Take a top-down recursive approach
    var len = arr.length;
    if(len < 2) {
        return arr;
    }
    var middle = Math.floor(len / 2),
        left = arr.slice(0, middle),
        right = arr.slice(middle);
    return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right){
    var result = [];
    console.time('Merge sort time');
    while (left.length && right.length) {
        if (left[0] <= right[0]) {
            result.push(left.shift());
        } else{ result.push(right.shift()); }}while (left.length)
        result.push(left.shift());
    while (right.length)
        result.push(right.shift());
    console.timeEnd('Merge sort time');
    return result;
}
Copy the code

6. Hill Sort

Use the step size to compare two elements, and then reduce the step size to sort. Hill sort is the essence of the group insertion sort, the method is also known as reduced incremental sort. The basic idea of the method is: will first stay the whole row element sequence is divided into several sub sequence (composed of elements separated by a “delta”) direct insertion sort, respectively, and then in turn to cut incremental sort, with the sequence of elements in the basic order (increment is small enough, again to all the elements on a direct insertion sort. Because direct insertion sort is efficient when the elements are basically ordered (close to the best case), Hill sort has a large increase in time efficiency. Differences from insertion sort:It’s going to give preference to the ones that are farther away

function shellSort(arr) {
  let temp,
    gap = 1;
  while (gap < arr.length / 3) {
    gap = gap * 3 + 1// Define the interval sequence dynamically
  }
  for (gap; gap > 0; gap = Math.floor(gap / 3)) {// Control the step size (interval) and reduce it
    for (var i = gap; i < arr.length; i++) {// Sort the sequence by the number of increments
      temp = arr[i]
      for (var j = i - gap; j >= 0 && arr[j] > temp; j -= gap) {// example: j=0 arr[1]>arr[5]
        arr[j + gap] = arr[j]
      }
      arr[j + gap] = temp
    }
  }
  return arr
}
Copy the code

7. Comparison of various sorting algorithms

Time complexity and space complexity

1. How to measure the advantages and disadvantages of different algorithms?

Mainly from the algorithm occupied by the “time” and “space” two dimensions to consider.

  • Time dimension: refers to the time taken to execute the current algorithm, which is usually described as “time complexity”.
  • Spatial dimension: Refers to the amount of memory space required to perform the current algorithm, which is usually described as “spatial complexity”.

2. Time complexity

1

“Big O notation”, i.e. T(n) = O(f(n))

The time complexity formula is: T(n) = O(f(n)), where f(n) represents the sum of the number of times each line of code is executed, and O represents the direct proportion. The full name of this formula is: the asymptotic time complexity of the algorithm.

2. Common complexity levels

• Constant order O(1) • logarithmic order O(logN) • Linear order O(n) • Linear logarithmic order O(nlogN) • Square order O(n²) • Cubic order O(n³) • K order O(n^ K) • Exponential order (2^n)

3. O(1)

No matter how many lines of code are executed, as long as there are no complex structures such as loops, the time complexity of the code is O(1).

var i = 1;
var j = 2;
++i;
j++;
var m = i + j;
Copy the code

4. O(n)

The code inside the for loop is executed n times, so the time it takes varies with n, so this type of code can be expressed as O(n).

for(i=1; i<=n; ++i)
{
   j = i;
   j++;
}
Copy the code

5. The logarithmic orderO(logN)

var i = 1;
while(i<n)
{
    i = i * 2;
}
Copy the code

In the while loop, every time I is multiplied by 2, I is getting closer and closer to n. So let’s try to solve for this, and let’s say that after I goes through x times, I is greater than 2, and then the loop ends, which means that 2 to the x is equal to n, so x is equal to log base 2 to the n, which means that after I go through log base 2 to the n, this code ends. So the time complexity of this code is: order logn.

6. O(nlogN)

So if you loop through a code that’s O logn times, then it’s N times O logn, which is O N logn.

for(m=1; m<n; m++)
{
    i = 1;
    while(i<n)
    {
        i = i * 2; }}Copy the code

7. O (n squared),O(m*n),O (n) after,O(n^k)

The square order O(n ^ 2), and the time complexity of nesting the O(n) code again, is O(n*n), which is O(n ^ 2).

for(x=1; i<=n; x++)
{
   for(i=1; i<=n; i++) { j = i; j++; }}Copy the code

O(m*n), change the n of one of the loops to m, and then the time complexity becomes O(m*n).

for(x=1; i<=m; x++)
{
   for(i=1; i<=n; i++) { j = i; j++; }}Copy the code

3. Space complexity

Space complexity is a measure of the amount of storage space temporarily occupied by an algorithm while it is running, and also reflects a trend, which is defined by S(n).

1. Common complexity levels

Common examples of space complexity are: O(1), O(n), and O(n²).

2. O(1)

If the temporary space required for algorithm execution does not change with the size of some variable n, that is, the algorithm space complexity is a constant, which can be expressed as O(1).

var i = 1;
var j = 2;
++i;
j++;
var m = i + j;
Copy the code

The space allocated by I, J, and m in the code does not change with the amount of data being processed, so its space complexity S(n) = O(1)

3. O(n)

var arr = [1.2.3]
for(i=1; i<=arr.lemgth; ++i)
{
   j = i;
   j++;
}
Copy the code

The first line defines an array, and the size of the data is n, and the 2-6 lines of this code, although there is a loop, there is no new space allocated, so the space complexity of this code depends on the first line, S(n) = O(n).

23. Interface request

1.AJAX

1. Simply implement oneajax

function stringify (json) {
  var str = "";
  for (var i in json) {
    str += i + "=" + json[i] + "&";
  }
  return str.slice(0, -1);
}
function myAjax (type, url, params, callback, errback) {
  let xhr = null;
  IE / / table
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (type == "get") {
    xhr.open(type, url + "?" + stringify(params), true);
    xhr.send();
  } else {
    xhr.open(type, url, true);
    xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
    // Convert json to name= span &age=1
    xhr.send(stringify(params));
  }
  xhr.onreadystatechange = function () {
    // Indicates that the request has been completed
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        if(callback) { callback(xhr.responseText); }}else{ errback && errback(); }}}}Copy the code

2,ajaxreadyStateThe state of the

  • 0Uninitialized, not called yetopen()methods
  • 1Start, already calledopen()Method, but not calledsend()methods
  • 2Send, already calledsend()Method, but the response has not yet been received
  • 3Received. Partial response data has been received
  • 4Done. All response data has been received

2,Axios

Axios is essentially a wrapper around native XHR, but it’s an implementation of Promise that complies with the latest ES specification

1. Features:

  • fromnode.jscreatehttprequest
  • supportPromise API
  • Client support for preventionCSRF
  • Provides some interfaces for concurrent requests (important, much easier)

3,Fetch

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method, which provides a simple, reasonable way to asynchronously fetch resources across the network.

1. The advantages

  • The syntax is concise and more semantic
  • Based on the standardPromiseImplement, supportasync/await
  • Isomorphism is convenient to useisomorphic-fetch

2. The shortcomings

  • FetchThe request defaults to nonecookie, need to be setfetch(url, {credentials: 'include'})
  • Not when the server returns a 400,500 error coderejectWhen the request cannot be completed due to network errors,fetchWill bereject.

24,newThe operator

1.newImplementation process of

  • Create a new object;
  • 2. Assign the scope of the constructor to the new object (thusthisRefers to the new object);
  • 3. Execute the code in the constructor (to add properties to the new object);
  • 4. Return the new object.
  • 5. Will the constructorprototypeAssociated with an instance__proto__

2. How to implement onenew

function myNew (foo, ... args) {
  // Create a new object that inherits Foo's Prototype property
    let obj = Object.create(foo.prototype)
  // Execute the constructor and bind the new this,
  let result = foo.apply(obj, args)
  // If the constructor returns an object, then that object is returned, otherwise the new object created by myNew is returned
  return Object.prototype.toString().call(result) === '[object Object]' ? result : obj
}
Copy the code

25. How to achieve full-screen web pages?

document.documentElement.requestFullscreen()
Copy the code

Compatible implementation required

1, web page full screen

function fullScreen() {
    if (!document.fullscreenElement &&
        !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) { // current working methods
        if (document.documentElement.requestFullscreen) {
            document.documentElement.requestFullscreen();
        } else if (document.documentElement.msRequestFullscreen) {
            document.documentElement.msRequestFullscreen();
        } else if (document.documentElement.mozRequestFullScreen) {
            document.documentElement.mozRequestFullScreen();
        } else if (document.documentElement.webkitRequestFullscreen) {
            document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); }}}Copy the code

2. Cancel full-screen web pages

function exitFullScreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen(); }}Copy the code

3. Check whether the screen is full

/** * Check whether the screen is full *@return {[Boolean]} [Full screen: true no full screen: false full screen] */
function checkFullScreenValue () {
    return !document.fullscreenElement &&
        !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement
}
Copy the code

26,Map,WeakMapset,WeakSetWhat’s the difference?

WeakMap and WeakSet are both weak references

1. What is a weak reference

A weak reference is a reference that has no assurance that the object it refers to will not be collected by the garbage collector, in other words it may be collected at any time.

Weak references disappear at any time, and the traversal mechanism cannot guarantee the existence of a member

2,Set

  • Traversal order: insertion order
  • There’s no key, there’s only a value, and you can think of the key and the value as equal
  • Add multipleNaN, only one will existNaN
  • When the same object is added, it is thought to be a different object
  • Casting does not occur when adding values (5! = = "5")
  • keys()values()Is exactly the same,entries()The returned iterator includes both the key and the value and the two values are equal

3,weakSetrole

  • andSetStructure similar, member values can only be objects
  • storageDOMNodes:DOMThis member is automatically released when the node is removed, without worrying about memory leaks when the nodes are removed from the document
  • Temporarily holds a group of objects or holds information bound to objects: as long as the objects disappear from the outside, it remainsWeakSetThe references in the structure are automatically eliminated
  • Members are weak references and are not considered by garbage collectionWeakSetStructure a reference to this member
  • Member is not suitable for reference, it will disappear at any time, soES6provisionsWeakSetThe structure is not ergodic
  • When other objects no longer reference the member, the garbage collection mechanism automatically reclaims the memory used by the member, regardless of whether the member still existsWeakSetIn the structure

4,Map

  • Traversal order: insertion order
  • If you assign a value to the same key more than once, the later value overrides the previous one
  • A reference to the same object is treated as a key
  • Two instances of the same value are treated as two keys
  • Keys are bound to memory addresses and are considered two keys as long as the memory addresses are different
  • Add more than oneNaNAs a key, there will only be oneNaNValue as a key
  • ObjectStructure provides the corresponding string – value,MapThe structure provides the value – the corresponding value

5,WeakMap

  • andMapSimilar structure, member keys can only be objects
  • storageDOMNodes:DOMThis member key is automatically released when the nodes are removed without worrying about memory leaks when they are removed from the document
  • Deploy private properties: Internal properties are weak references to the instance and disappear when the instance is deleted without causing a memory leak
  • Member keys are weak references and are not considered by garbage collectionWeakMapStructure a reference to this member key
  • The member key is not suitable for reference, it will disappear at any time, soES6provisionsWeakMapThe structure is not ergodic
  • When other objects no longer reference the member key, the garbage collection mechanism automatically reclaims the memory used by the member, regardless of whether the member still existsWeakMapIn the structure
  • Once the member is no longer needed, the member automatically disappears without manually deleting the reference
  • A weak reference is a key, not a value, and the value is still a normal reference
  • Even if the reference to the member key is removed externally, the internal member value still exists

6,ObjecttoMap

let obj = {"a":1."b":2};
let map = new Map(Object.entries(obj))
Copy the code

27,Proxy

1, grammar,

  • targetIn order to useProxyThe wrapped target object (which can be any type of object, including a native array, a function, or even another proxy)
  • handlerAn object, usually a function as a property, that is used to customize interception behavior

The proxy has no effect on proxy objects, but only on proxy objects

origin = {}
obj = new Proxy(origin, {
  get: function (target, propKey, receiver) {
        return '10'}}); obj.a/ / 10
obj.b / / 10
origin.a // undefined
origin.b // undefined
Copy the code

2,HandlerObject

methods describe
handler.has() inOperator.
handler.get() Property read operations.
handler.set() Property set action.
handler.deleteProperty() deleteOperator.
handler.ownKeys() Object.getOwnPropertyNamesMethods andObject.getOwnPropertySymbolsMethod.
handler.apply() A catcher for a function call operation.
handler.construct() newOperator
# # # 3,proxyCan an agent be revoked?
proxyThere’s a unique static method,Proxy.revocable(target, handler)
Proxy.revocable()Method can be used to create an undoable proxy object
The return value of this method is an object with the structure: {"proxy": proxy, "revoke": revoke}
  • proxyRepresents the newly generated proxy object itself, and in a general mannernew Proxy(target, handler)The proxy object created is no different, except that it can be destroyed.
  • revokeThe undo method, called without any arguments, destroys the generated proxy object.
const target = { name: 'vuejs'}
const {proxy, revoke} = Proxy.revocable(target, handler)
proxy.name // Output vuejs in normal value
revoke() // Close the proxy and undo the proxy
proxy.name // TypeError: Revoked // Revoked
Copy the code

28. Execution context

1. What type of execution context?

1. Global execution context:

Only one global execution context can exist in a program.

This is the default, most basic execution context. Code that is not in any function is in the global execution context. It does two things:

  1. Create a global object. In the browser, the global object iswindowObject.
  2. willthisThe pointer points to this global object.

2. Function execution context:

There can be an infinite number of function execution contexts.

Each time a function is called, a new execution context is created for that function. Each function has its own execution context, but it is created only when the function is called.

3. EvalFunction execution context:

The eval function of js creates its own execution context and is rarely used and not recommended.

2. Features of execution context

  1. Single thread;
  2. Synchronous execution, sequential execution from top to bottom;
  3. There is only one global context, namelywindowObject;
  4. There is no limit to the number of function execution contexts;
  5. A function is created only when it is called, creating a new execution context each time it is called.

The lifecycle of the execution context

1. Create phase

  1. Create a variable object: First initialize the parameters of the functionargumentsTo promote function declarations and variable declarations.
  2. Create a scope chain: The scope chain is created after the variable object. The scope chain itself contains variable objects. The scope chain is used to parse variables. When asked to parse variables,JavaScriptAlways start at the innermost level of the code nesting, and if the variable is not found in the innermost level, it jumps to the parent scope at the previous level until it is found.
  3. determinethisPoint to: determinethisPointing to.

2. Execution phase

  1. Perform variable assignment.
  2. Function references.
  3. Execute other code.

3. Recycle

  1. Execute context off stack
  2. Wait for the VM to reclaim the execution context

4,jsHow to manage multiple execution contexts?

Managing multiple execution contexts relies on the execution stack, also known as the call stack.

Features: LIFO: last-in, first-out (LIFO) structure. Function: All execution contexts stored during code execution.

Example:

var a = 1; // 1. Global context
function bar (x) {
    console.log('bar')
    var b = 2;
    fn(x + b); // 3. Fn context
}
function fn (c) {
    console.log(c);
}
bar(3); // 2. Bar context
Copy the code

Implement some special functions

1. One-time functions

function once (func) {
  let done;
  return function () {
    if(! done) { func.apply(null.arguments)
      done = true}}}const onlyDoOne = once(function() {
  console.log('1')
})
onlyDoOne() / / 1
onlyDoOne() // No output, no reexecution
Copy the code

2. Delay function (sleep function)

function sleep (time) {
    return new Promise(resolve= > {
    window.setTimeout(resolve, time)
  })
}
/ / call
sleep(1000).then(res= > {
    console.log('delay')})/ / call
async function useSleep () {
    const sleepval = await sleep(1000)
}
useSleep()
Copy the code

3,setTimeoutimplementationsetInterval

; (() = > {
  const list = new Set(a);function myInterval(fn, ms) {
    const ref = {};
    const exec = () = > {
      return setTimeout(() = > {
        fn.apply(null);
        const timer = exec();
        ref.current = timer;
      }, ms);
    };
    ref.current = exec();
    list.add(ref);
    return ref;
  }
  function myClearInterval(ref) {
    clearTimeout(ref.current);
    list.delete(ref);
  }
  window.myInterval = myInterval;
  window.myClearInterval = myClearInterval;
})()
myInterval(() = > {console.log(1)}, 5000)
myClearInterval({current: 1186})
Copy the code

4. Front-end generationexcelForm and download

/** * Front download form *@param  {[Array]} Data [Data array] *@param  {[String]} TableHead [table header string] *@return {[undefined]}           * /
function downExcel (data, tableHead) {
  tableHead = tableHead
  data.forEach(item= > {
    for (let i in item) {
      tableHead += `${item[i] + '\t'}, `
    }
    tableHead += '\n'
  })
  const url = 'data:text/csv; charset=utf-8,\ufeff' + encodeURIComponent(tableHead);
  // Do this by creating a tag
  const link = document.createElement("a");
  link.href = url;
  // Name the downloaded file
  link.download = "My EXCEL spreadsheet.csv.";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
/ / the excel data
let tableData = [{
  name: 'Hello'.time: 130000000000.pre: '127.130'.source: 'taobao'.otherTime: 1571276232000
}]
/ / excel in the head
let str = 'User name, time, coordinates, source, authorization time \n';
// Download the form to execute
downExcel(tableData, str)
Copy the code

What are prototypes and prototype chains?

Stereotype: When a constructor (a function used to instantiate an object) is declared in JS, a corresponding object is created in memory. This object is the stereotype of the original function.

By default, constructors have a Prototype property, whose value refers to the prototype of the function. The stereotype also has a constructor property whose value points to the original function.

An object instantiated by a constructor does not have the prototype property. By default, it has a __proto__ property, with the __proto__ value pointing to the constructor’s prototype object. Properties added or modified on prototype objects are shared on all instantiated objects.

When a property is accessed in an instantiated object, it is first looked inside the object and, if not found, directed to it__proto__If you can’t find it, continue to the prototype__proto__Pointing to the superior archetype until it finds orObject.prototypeSo far, this chain process isPrototype chain.

31. Achieve oneEventBus

Simple implementation

class myEventBus {
  constructor(props) {
    this.events = {}
  }
  on (event, fn) {
    const events = this.events events[event] ? events[event].push(fn) : (events[event] = [fn]) } emit (event, ... res) {this.events[event] && this.events[event].forEach(fn= > {
      return fn.apply(this, res)
    })
  }
  remove (event, fn) {
    if (this.events[event]) {
      delete this.events[event]
    }
  }
}
Copy the code

32,jsGarbage collection (GC)

1.V8Memory limit

  • The 64-bit system has 1.4 GB of memory available
  • The 32-bit system has 0.7 GB of memory available

2,V8Memory management

  • JSObjects are all passedV8To allocate and manage memory
  • process.memoryUsage()Returns an object containingNodeMemory usage of a process

3. Memory usage structure diagram

  • Var a = {name: "yuhua"};This code does the following:
    • Put this code in the “code area”Code Segment
    • The variableaIn the stack (Stack) : local variable, pointer”
    • will{name: "yuhua"}In the”HeapTotal(Heap) : Object, closure”
  • Note: The basic data types are in the stack, and the reference types are in the heap

4. Why limit memory size

  • becauseV8Because of the working principle of garbage collection, it takes more than 1 second for 1.4 GB of memory to complete a garbage collection
  • This garbage collection time (pause time) becomesStop The WorldDuring this period, the performance and responsiveness of the application will degrade

5,V8Garbage collection mechanism

  • V8Is based on generational garbage collection
  • Different generation of garbage collection mechanism is different, using different algorithms
  • According to the time of inventory is divided into the new generation and the old generation

6, generational

  • The younger is the new generation, led byFromRegional andToRegion Consists of two regions
  • On 64-bit systems, the new generation of memory is 32 megabytes,FromRegional andToEach area occupies 16M
  • In 32-bit systems, the new generation of memory is 16 megabytes,FromRegional andToEach area is 8M
  • The older generation is the old generation, by default:
    • The old generation memory on 64-bit systems is 1400M
    • The old generation memory for 32-bit systems is 700M

7. The New generation adoptsScavengealgorithm

Scavenge is an algorithm used by the new generation. It is a garbage collection algorithm realized by means of copying.

This is a breadth-first scanning strategy

It divides memory into from and to Spaces. With each GC, the living objects from space are copied to the to space. Then the two spatial roles are reversed (also known as inversion).

This algorithm is to sacrifice space for time, so it is suitable for the new generation, because its object life cycle is short.

1. The process

  • The Cenozoic area is divided into two parts, each 16M, one in use and one idle
  • When you start garbage collection, you checkFROMThe surviving objects in the region, if still alive, are copied toTOSpace to clear (free) after all living objects have been copied.FROMarea
  • Then the FROM and To fields are interchanged

Characteristics of 2.

  • This is a breadth-first scanning strategy
  • The new generation of space is small, the survival of fewer objects
  • While an object manager is still alive after multiple garbage collections, objects with a poor lifetime are moved to the old cords, a process known as promotion or upgrade
  • It has been recycled more than 5 times
  • TOMore than 25% of the space used, or oversized objects
  • The browsermemoryYou can take a snapshot to see if the variable is garbage collected
  • Set toundefinednullCan subtract 1 from the reference count

8, the old generation adoptedMark-SweepMark-Compact

1. The basic

  • There are two types of old generation garbage collection strategies
    • mark-sweepMark clear
      • Mark living objects, although it is clear that there are no marked objects during the mark phase, and only dead objects are cleaned up

      Problems that may occur: Memory is discontinuous after clearing, and fragmented memory cannot be allocated

    • mark-compactTag to sort out
      • When the mark is dead, the object will be organized, moving left alive, and clearing memory outside the boundary (dead objects) after the move is complete.
  • Older generations have a lot of space and are mostly living objects,GCIt takes a long time
  • inGCI can’t listen to it,STOP-THE-WORLD
  • V8One optimization, incremental processing, replaces one large pause with multiple small pausesINCREMENT-GC
  • By splitting a large pause into smaller pauses, each with the application running for a short period of time, the garbage collection and the application alternate and the pause time can be reduced to about a sixth

Process of 2.

Let’s say I have 10 sizes of memory and memory takes up 6 of them,

1)Mark-SweepMode garbage collection:
  • Then each object will be marked:
A b C D E f null null null null // Mark each of the above objects. Uppercase means alive and lowercase means dead // At this point, there will be A problem that the memory fragments will not be used, because the lowercase memory is not placed with the empty memoryCopy the code
  • In this case, the lower case (dead) will be killed and only the upper case (alive) will be left, resulting in the problem of memory fragmentation
2)Mark-CompactMode garbage collection
  • Move the live one to the left
A C E B D F Empty empty empty emptyCopy the code
  • Then recycle the dead area
A C E Empty empty empty empty empty emptyCopy the code

9. Comparison of three algorithms

Recovery algorithm Mark-Sweep Mark-Compact Scavenge
speed medium The slowest The fastest
The space overhead less less Double space (no debris)
Move object or not no is is
  • V8It is mainly used in the old generationsMark-SweepBecause theMark-CompactObjects need to be moved and execution is slow. Only when we run out of spaceMark-Compact

33. Design Patterns

1. Design Principles:

1. Single Responsibility Principle (SRP)

An object or method does only one thing.

2. Minimum Knowledge Principle (LKP)

Interactions between objects should be minimized.

3. Open-closed Principle (OCP)

Software entities (classes, modules, functions), etc., should be extensible, but not modifiable

2. Policy mode

The strategy pattern is to define a set of algorithms, encapsulate each algorithm, and make them interchangeable. The strategy pattern allows the algorithm to change independently of the customers who use it. Advantages:

  • The policy pattern uses techniques and ideas like composition and delegation to avoid many if statements
  • The policy pattern provides an open-close principle that makes code easier to understand and extend

Example:

  1. Performance rating and salary calculation bonus is
  2. Form validation usually involves validation of multiple fields

3. Cache proxy pattern

The caching proxy can provide temporary storage for some expensive operation results. In the next operation, if the parameters passed in are the same as the previous one, it can directly return the previously stored operation results, providing efficiency and cost savings.

A cache proxy is a proxy that caches the previously used values and then uses them if they are still in use.

4. Factory mode

The factory pattern is one of the most common design patterns used to create objects. Instead of exposing the concrete logic that created the object, we will encapsulate the logic in a function that can then be treated as a factory. The factory pattern can be divided into simple factories, factory methods, and abstract factories, depending on the degree of abstraction.

The advantage of a simple factory is that you only need one correct argument to get the object you need without having to know the details of how it was created. A simple factory can only be used when a small number of objects are created and the object creation logic is not complex.

The idea of the factory method pattern is to postpone the actual creation of objects to subclasses. The factory method pattern is to split the large factory into smaller factories. Each time a new product is added, the small factory produces it, and the large factory directs it.

The abstract factory pattern does not generate instances directly, but is used for the creation of clusters of product classes.

5. Singletons

Ensure that there is only one instance of a class and provide a global point of access to it.

Ensures that there is only one instance

  • Because there are only one instance, system resources are saved, and remember that creating and destroying also wastes memory resources
  • It avoids multiple occupation of resources, such as database connections
  • Resource sharing

Front-end application scenario:

  • The browserwindowObject. inJavaScriptIn development, singletons are often used for objects that only need one.
  • Cover layer, landing float window, etc.

6. Proxy mode

Provides a substitute or placeholder for an object in order to control access to it.

There are three types of proxy modes: protected proxy, virtual proxy, and cache proxy

7. Iterator pattern

The iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing the internal representation of the object.

JS already has built-in iterators for map forEach arrays

Publish – subscriber model

Also known as the observer pattern, it defines a one-to-many dependency between objects. When an object’s state changes, all objects that depend on it are notified.

Events in JS are an implementation of the classic publish-subscribe pattern

9. Command mode

Design your program in such a loosely coupled way that the request sender and the request receiver can decouple from each other. A command is an instruction that does something specific

34. Functions & self-executing functions

1. Features of self-executing function

  1. Unlike a function declaration, a function name is valid only within the function, and the binding is a constant binding.
  2. Assign to a constant atstrictAn error is reported in modestrictSilent failure in mode.
  3. IIFEThe functions in are function expressions, not function declarations.

2. Function type

  1. Function declaration
  2. Function expression
  3. Function constructor is created

1. Function declaration (FD)

  1. There’s a particular name for it
  2. Location in the source code: either at the program level (Program level), or in the body of another function (FunctionBody)
  3. Created during the enter context phase
  4. Influence variable object
  5. Declare it as follows
function funName () {}
Copy the code

2. Function expression (FE)

  1. Must appear in the source code at the position of the expression
  2. There are optional names
  3. Does not affect variable objects
  4. Created during the code execution phase
// Function expression
var foo = function () {} // Assign an anonymous function expression to the variable foo
var foo2 = function _foo2() {} // External FE is accessed through the variable "foo" -- foo(), while inside the function (such as a recursive call), it is possible to use the name "_foo".
// Only expressions can be inside parentheses (grouping operators)
(function foo() {});
// Only expressions are allowed inside the array initializer
[function bar() {}];
// Commas can only operate on expressions
1.function baz() {};
// !
!function() {} (); (function foo() {}) ()// The self-executing function IIFE
(function () {}) ()// IIFT
var foo = {
  bar: function (x) {
    return x % 2! =0 ? 'yes' : 'no'; } (1)}; foo.bar// 'yes'
Copy the code

3. The function created by the function constructor

We distinguish it from FD and FE. The main feature of this function is that the [[Scope]] attribute contains only global objects

var x = 10;
function foo() {
  var x = 20;
  var y = 30;
  var bar = new Function('alert(x); alert(y); ');
  bar(); // 10, "y" is undefined
}
Copy the code

3, how to create a function that does not need () to execute

  1. Create an object
  2. An expression in an object defines a self-executing function
var foo = {
  bar: function (x) {
    return x % 2! =0 ? 'yes' : 'no'; } (1)}; foo.bar// 'yes'
Copy the code

4. Why are some of them added(a)Some can be left out?

The grouping operator parentheses are required when the function is not located in the expression — that is, to manually convert the function to FE.

If the parser knows it’s dealing with FE, there’s no need to use parentheses.

5. Named function expression

An important feature occurs when the function expression FE has a name (called named function expression, abbreviated NFE).

We know from the definition (as we saw from the above example) that a function expression does not affect a contextual variable object (that means that it is neither possible to call a function by name before it is declared nor after it is declared). However, FE can call itself by name in a recursive call.

(function foo(bar) {
  if (bar) {
    return;
  }
  foo(true); // "foo" is available}) ();Copy the code

Where is “foo” stored? In the live object of Foo? No, because there is no “foo” defined in foo. Create foo? In the context’s parent variable object. No, because by definition — FE doesn’t affect VO (variable object) — calling foo from the outside can be seen. So where is it?

When the interpreter encounters a named FE during the code execution phase, before the FE is created, it creates auxiliary specific objects and adds them to the forefront of the current scope chain. It then creates FE, at which point (as we learned in Chapter 4: Scope Chain) the function gets the [[Scope]] attribute — the Scope chain that creates the function context. After that, the name of FE is added to the specific object as a unique attribute; The value of this attribute is referenced to FE. The final step is to remove that particular object from the parent scope chain.

6. Examples of self-executing functions

/ / a
+function foo(){
foo=10;// My problem code
    console.log(foo);// Methods themselves} ();console.log(typeof foo);// Use undefined to observe global contamination

/ / two cases
var b = 10;
(function b() {
   // Select * from 'b' where 'b' = '20' where 'b' = '20' where 'b' = '20'; Function b(){};
   // IIFE functions cannot be assigned (internal mechanism, similar to const defined constants), so they are invalid.
  // The IIFE is stored in the JS stack. // The IIFE is stored in the JS stack.
    b = 20;
    console.log(b); // [Function b]
    console.log(window.b); // 10, not 20}) ();// Strict mode will report an error
var b = 10;
(function b() {
  'use strict'
  b = 20;
  console.log(b)
})() // "Uncaught TypeError: Assignment to constant variable."

// Normal function
function a () {
    a = 1
    console.log(a)
}
a() / / 1
a() // a is not a function
Copy the code

35,XSSAttacks andCSRFattack

1.XSSattack

1. The concept

Cross Site Scripting (XSS) : Cross-domain Scripting attacks.

Principle 2.

It does not require you to do any login authentication, it will inject scripts (js, HMTL blocks, etc.) into your page through legitimate actions (such as typing in the URL, typing in the comment box).

3. To prevent

  1. Coding; Encode user input.
  2. Filtering; Removes attributes associated with user input and events. (filterscript,style,iframeSuch as node)
  3. Correction; useDOM ParseConvert, correct for unpairedDOMThe label.
  4. HttpOnly.

Classification of 4.

  • Reflective (non-persistent) : Click the link and execute the script
  • Stored (persistent) : Malicious input saved to the database, other users access, execute scripts
  • Based on theDOM: Malicious modificationDOMStructure, based on client

2,CSRFattack

1. The concept

Cross-site request forgery (SRF) : Cross-site request forgery.

Principle 2.

  1. Log on to trusted sitesAAnd is generated locallyCookie. (If the user is not logged in to the siteA, then the websiteBDuring induction, request the siteAapiInterface, will prompt you to log in).
  2. Without logoutAIn case of visiting dangerous websitesB(Actually use the websiteA).

3. To prevent

  1. tokenValidation;
  2. Hide the token; thetokenHidden in thehttpThe request ofheadIn the.
  3. refererValidation; Verify the source of the page.

3. Differences between the two

  1. CSRF: Requires the user to log in to the websiteATo obtaincookie.XSS: No login is required.
  2. CSRF: is to use the websiteAThe bug itself, go to the request websiteAapi.XSS: is to the websiteAinjectionJSCode, and then executeJSTo tamper with the siteAThe content of the.

36,inputInput box input is request back-end interface, after frequent requests how to determine the last interface return value?

1, back end return request value (simplest)

When the front end requests the interface, it will send the value in the input box to the back end. At this time, the back end will return the value passed in the front end when it returns the interface data, and only need to make a judgment when rendering the page.

2. Terminate the last request

Terminate the previous request when asked again:

  1. ajax:abort()
  2. axios: CancelToken
  3. fetch:AbortController

This is what Baidu uses to cancel requests

Js:ss1.bdstatic.com/5eN1bjq8AAU…

3. Define a globalID, before the interface request increment, and then request the interface closure to save this value, and make the judgment after the return.

In this way, the value returned by the back end is not used, and the value information stored by the front end is used for judgment and processing

implementation

let id = 1
function ajax() {
  ++id
  console.log(id)
  function getData () {
    const newId = id
    const time = Math.random() * 5000 | 0 // Define a random value
    console.log('time', time)
    setTimeout(() = > {
      console.log('id newId', id, newId)
      if (id === newId) { // This is where the data is processed
        console.log('this is true-->', id)
      }
    }, time)
  }
  getData()
}
// Click the start function frequently
document.getElementById('ajaxbtn').onclick = function () {
  ajax()
}
Copy the code

37,rem

1, define,

Rem (Font size of the root Element) is the unit of font size relative to the root element. 1rem is equal to the font-size of the root element HTM, that is, only the font-size of the root element needs to be set. When the unit of REM is used for other elements, the corresponding percentage can be set.

2. How

Rem (multiple) = width/(HTML) => width = (HTML) * REM (multiple)Copy the code

As long as the FONT size of HTML changes, the width will automatically change, so REM changes the width by dynamically setting the FONT size of HTML, so as to achieve the purpose of adaptive size of web pages

Rem (multiple) = width/(HTML)

Rem = imgWidth/the size(defalutSize) you set. Rem = screenWidth/the size(x) you need to set dynamically. The formula for setting HTML’s font-size is:

<script type="text/javascript">
  (function(w,d) {
  function setSize() {
    var screenWidth = d.documentElement.clientWidth;
    var currentFontSize = screenWidth * 100 / 750;
    d.documentElement.style.fontSize = currentFontSize + 'px';
  }
  w.addEventListener('resize',setSize);
  w.addEventListener('pageShow',setSize)
  w.addEventListener('DOMContentLoaded',setSize)
})(window.document)
</script>
Copy the code
function setHtmlSize(){
  var pageWidth = window.innerWidth;
  if(typeofpageWidth ! ="number") {if(document.compatMode == "number"){ 
      pageWidth = document.documentElement.clientWidth;
    }else{ 
      pageWidth = document.body.clientWidth; }}var fontSize = (window.innerWidth * 100) / 750;
  if(fontSize<40){
    fontSize = 40;
  }
  // Determine the root node size based on the screen size
  document.getElementsByTagName('html') [0].style.fontSize = fontSize + 'px';
}
function resize(){
  setHtmlSize();
}
if (window.attachEvent) { 
  window.attachEvent("resize", resize); 
} else if (window.addEventListener) { 
  window.addEventListener("resize", resize, false);   
}
setHtmlSize();
Copy the code

3,750The width,1rem = 100px.iphone6/7/8 plusSet in theWidth: 6.5 remWhat is the width of the element?

The width in plus is 414, so the width is 414/750 * 6.5 * 100. 0.32rem is 414/750 * 0.32 * 100

Thirty-eight,dns-prefetch,prefetch,preload,defer,async

1.dns-prefetch

Converting domain names to IP is a time-consuming process, and DNS-Prefetch lets you do it for you when your browser is idle. In particular, large websites use multiple domain names, which makes DNS prefetch even more necessary.

// from baidu homepage<link rel="dns-prefetch" href="//m.baidu.com">
Copy the code

2,prefetch

Prefetch is used to preload resources that may be used. It is a judgment of user behavior. The browser loads prefetch resources when it is idle.

<link rel="prefetch" href="http://www.example.com/">
Copy the code

3,preload

Unlike prefetch, a prefecth usually loads resources for a page that may be used later. Preload loads resources such as scripts, styles, fonts and pictures for the current page. So instead of loading at idle, preload has a higher priority and consumes the number of HTTP requests.

<link rel='preload' href='style.css' as="style" onload="console.log('style loaded')"
Copy the code

asValue including

  • script
  • style
  • image
  • media
  • document onloadA method is a callback function that completes resource loading

4,deferasync

//defer
<script defer src="script.js"></script>
//async
<script async src="script.js"></script>
Copy the code

Both Defer and async load resources asynchronously (in parallel). The difference is that async executes immediately after loading, while defer does not execute until all elements are parsed, that is, before the DOMContentLoaded event is triggered. Because the resource loaded by async is loaded for execution, it is not guaranteed to be in order, and defer executes the script in order.

39. Browser rendering process

1. The browser rendering process is as follows

  • parsingHTMLTo generate theDOM
  • parsingCSSTo generate theCSSOM
  • willDOMTrees andCSSOMTree combination to generate a rendered tree (Render Tree)
  • Layout(Backflow) : Based on the generated render tree, backflow (Layout) to get the geometric information (location, size) of the node
  • Painting(redraw) : Obtain the absolute pixels of a node based on the geometric information obtained from the rendered tree and backflow
  • Display: sends pixels toGPUIs displayed on the page. (This step is actually a lot of content, such as inGPUCombine multiple composition layers into a single layer and display it on a page. whilecss3Hardware acceleration works by creating a new composition layer.)

2. When to trigger backflow and redraw

1. Return

  • Add or remove visibleDOMThe element
  • The position of the element changes
  • Element size changes (margin, inner border, border size, height, width, and so on)
  • Content changes, such as text changes or an image is replaced by another image of a different size.
  • The first time the page is rendered (which I can’t avoid)
  • Browser window size changes (because backflow calculates the position and size of elements based on viewport size)

2. Redrawn

  • Backflow is bound to trigger a redraw
  • When a change in the style of an element on a page does not affect its position in the document flow (for example:color,background-color,visibilityEtc.), the browser assigns the new style to the element and redraws it, a process called redrawing.

3, if avoid triggering backflow and redraw

1. css

  • Avoid the use oftableLayout.
  • As far as possible inDOMThe end of the tree changesclass.
  • Avoid setting multiple inline styles.
  • Apply the animation effect topositionProperties forabsolutefixedOn the elements of
  • Avoid the use ofCSSExpressions (e.g.calc())
  • CSS3Hardware acceleration (GPUAcceleration)
    • transform
    • opacity
    • filters
    • Will-change

2. JavaScript

  • Avoid frequent manipulation of styles. It is better to rewrite them all at oncestyleProperty, or define the style list asclassAnd change it onceclassProperty, modifystylecssTextAttribute or modify the elementclassNameValue.
  • Avoid frequent operationsDOM, create adocumentFragment, apply allDOMAction, and finally add it to the document
  • You can also set it for the element firstdisplay: noneAnd then display it after the operation is over. Because in thedisplayProperties fornoneOn the elements ofDOMOperation does not cause reflux and redraw
  • Avoid reading properties that cause reflow/redraw too often, and if you do need to use them more than once, cache them with a single variable
  • Use absolute positioning for elements with complex animations to take them out of the document stream, otherwise causing frequent backflow of the parent and subsequent elements.
  • usecss3Hardware acceleration can allowtransform,opacity,filtersThese animations do not cause a backflow redraw. But for other properties of the animation, such asbackground-colorThese will still cause backflow redraws, but it will improve the performance of these animations.

4. Hardware acceleration principle

When the browser receives the page document, it parses the markup language in the document into a DOM tree. The DOM tree is combined with CSS to form a rendering tree for the browser-built page. The render tree contains a large number of render elements. Each render element is divided into a layer, and each layer is loaded onto the GPU to form the render texture. The transform of the layer on the GPU does not trigger repaint. Ultimately, all layers that use Transform are handled by a separate synthesizer process.

1. When does the browser create a separate composite layer?

  • 3DorCSS transform
  • <video><canvas>The label
  • CSS filters
  • Element, such as usingz-indexattribute

The difference between 3D and 2D Transform is that the browser creates a separate composite layer for the 3D animation before rendering the page, and creates it for the 2D animation at run time. When the animation starts, a new composite layer is generated and loaded as a TEXTURE for the GPU to initialize repaint. The GPU’s compositor then manipulates the execution of the entire animation. Finally, when the animation is over, perform the repaint operation again to remove the composite layer.

2. Problems with hardware acceleration

  • Memory. ifGPUWith lots of textures loaded, it’s easy to run into content problems, especially on mobile browsers, so it’s important to keep in mind that every element of the page is not hardware-accelerated.
  • useGPURendering affects the anti-aliasing effect of fonts. This is becauseGPUCPUThere are different rendering mechanisms. Even if the hardware acceleration eventually stops, the text will appear blurry during the animation.

Forty,JSBridge

1. What isJSBridge

JSBridge is a JS implementation Bridge that connects Native and H5 at both ends of the Bridge. It is convenient for Native to call JS in APP, and JS to call Native, which is a two-way communication channel. JSBridge mainly provides the ability of JS to call Native code and realize Native functions such as viewing local photo albums, opening cameras, fingerprint payment, etc.

2,H5nativeThe difference between

name H5 Native
The stability of Call system browser kernel, stability is poor Use the native kernel for greater stability
flexibility Fast version iteration, flexible online Iteration is slow, app store approval is required, and rollout speed is limited
The network speed is affected larger smaller
fluency Sometimes the load is slow, giving the user the feeling of “stalling” It loads faster and is more fluid
The user experience The function is limited by the browser, and the experience is sometimes poor The original systemapiRich, can achieve more functions, better experience
portability Compatible across platforms, such asPCWith the mobile terminal,iOSAndroid Low portability foriOSAndroidTwo sets of code need to be maintained
# # # 3,JSBridgeThe purpose of the
JSBridgeAs in the name”Bridge“Is the same as” isNativeAnd theNativeBetween the bridge, its core is to buildNativeAnd theNativeA channel for message communication between two – way communication.
2. A two-way communication channel:
  • JSNativeSending messages: calling related functions and notificationsNativeThe currentJSAnd so on.
  • NativeJSSend messages: trace back call results, message push, notificationJSThe currentNativeAnd so on.

4,JSBridgeprocess

H5 -> Triggers a URL in some way -> Native captures the URL and analyzes it -> Native does processing -> Native calls the JSBridge object passing callback to H5.

The implementation process

  • Step 1: Design oneNativeJSGlobal bridge object for interaction
  • The second step:JSHow to callNative
  • Step 3:NativeHow to learnapiIs called
  • Step 4: Analyzeurl-Parameter and callback format
  • Step 5:NativeHow to callJS
  • Step 6:H5apiMethod registration and format

5,JSBridgeThe realization principle of

  • JavaScriptcallNativeInjection is recommendedAPIThe way (iOS6Ignore,The Android 4.2Use the followingWebViewClientonJsPromptWay).
  • NativecallJavaScriptThe spliced command is executed directlyJavaScriptCode.

React Native iOS side example: JavaScript running in JSCore can actually be implemented in the same way as above, using the injection API to implement JavaScript calling Native function. However, React Native is not designed for JavaScript to call object-c directly. Instead, in accordance with the event response mechanism in Native development, React Native is designed to trigger the call through the return value when object-c calls JavaScript. The principle is basically the same, but the implementation is different.

1. NativeJS

1) android

Native calls to JS are easy, as long as you follow the “javascript: method name (‘ arguments, need to be converted to strings’)” rule.

mWebView.evaluateJavascript("Javascript: method name (' parameter, needs to be converted to string ')".new ValueCallback() {
        @Override public void onReceiveValue(String value) { }}}}}}}}}}
});
Copy the code
2)IOS

Native Html binding through stringByEvaluatingJavaScriptFromString calls on the window function.

2. JSNative

1) android

Native adds exposed JS bridge objects by addJavascriptInterface, and then declares the corresponding API methods inside the object.

private Object getJSBridge(a){  
    Object insertObj = new Object(){ @JavascriptInterface public String foo(a){ return "foo";  
        } @JavascriptInterface public String foo2(final String param){ return "foo2:"+ param; }};return insertObj;  
}
Copy the code
2)IOS

By introducing the official JavaScriptCore library in Native (iOS7 +), you can then bind the API to JSContext (then javascript in Html can be called by default through windox.top.*).

6,JSBridgeInterface implementation

The JSBridge interface has two functions: calling Native (sending messages to Native) and receiving Native messages (receiving messages).

1. Messages are one-way, so callNativeWhen the functionCallbackHow does that work?

JSBridge Callback is actually the Callback mechanism of RPC framework. It can also be explained by a simpler JSONP mechanism:

When sending a JSONP request, the url parameter will have a callback parameter, which is unique to the current page, and this parameter value will be the key to store the callback function in the window. Later, the server returns a script, which will also use this parameter value as a handle to call the corresponding callback function.

The unique identifier of the callback parameter is the key to the callback logic. In this way, we can follow this logic to implement JSBridge: use an increasing unique ID to identify and store the callback function, and pass this ID as a parameter to Native, and Native also uses this ID as the identifier of backtracking. In this way, the Callback Callback logic is implemented.

(function () {
    var id = 0,
        callbacks = {},
        registerFuncs = {};
    window.JSBridge = {
        / / call Native
        invoke: function(bridgeName, callback, data) {
            // Determine the environment and obtain different NativeBridges
            var thisId = id ++; // Get the unique ID
            callbacks[thisId] = callback; / / store the Callback
            nativeBridge.postMessage({
                bridgeName: bridgeName,
                data: data || {},
                callbackId: thisId // Pass to the Native end
            });
        },
        receiveMessage: function(msg) {
            var bridgeName = msg.bridgeName,
                data = msg.data || {},
                callbackId = msg.callbackId, // Native returns callbackId intact
                responstId = msg.responstId;
            // Concrete logic
            // bridgeName and callbackId do not exist at the same time
            if (callbackId) {
                if (callbacks[callbackId]) { // Find the corresponding handle
                    callbacks[callbackId](msg.data); // Execute the call
                }
            } elseif (bridgeName) {
                if (registerFuncs[bridgeName]) { // Find the handle via bridgeName
                    var ret = {},
                        flag = false;
                    registerFuncs[bridgeName].forEach(function(callback) = >{
                        callback(data, function(r) {
                            flag = true;
                            ret = Object.assign(ret, r);
                        });
                    });
                    if (flag) {
                        nativeBridge.postMessage({ / / callback Native
                            responstId: responstId,
                            ret: ret }); }}}},register: function(bridgeName, callback) {
            if(! registerFuncs[bridgeName]) { registerFuncs[bridgeName] = []; } registerFuncs[bridgeName].push(callback);// Store the callback
        }
    };
})();
Copy the code

7,JSBridgeHow to reference

By 1.NativeEnd injection

Injection method is similar to Native calling JavaScript, directly executing the bridge’s entire code.

Advantages: The version of the bridge is the same as that of the Native version. The Native version does not need to be compatible with different versions of JSBridge. At the same time,

Disadvantages: the timing of injection is uncertain. It needs to implement the mechanism of retry after the injection fails to ensure the success rate of injection. Meanwhile, the JavaScript side needs to take precedence when calling the interface.

By 2.JavaScriptThe reference

Execute directly with JavaScript.

Advantages: JavaScript side can determine the existence of JSBridge, direct call; Disadvantages: If the Bridge implementation changes, JSBridge needs to be compatible with multiple versions of Native Bridge or Native Bridge needs to be compatible with multiple versions of JSBridge.

41,web worker

1. What isweb worker? What are the benefits? What are the problems?

Web workers create multi-threaded environments for JavaScript, allowing the main thread to create Worker threads and assign some tasks to the latter. While the main thread is running, the Worker thread is running in the background, and the two do not interfere with each other. Wait until the Worker thread completes the calculation task, and then return the result to the main thread.

benefit:

The benefit is that when some computation-intensive or high-latency tasks are carried by Worker threads, the main thread (usually responsible for UI interaction) will be smooth and not blocked or slowed down.

Question:

Once the Worker thread is created successfully, it will always run and not be interrupted by activities on the main thread (such as the user clicking a button or submitting a form). This helps to respond to the main thread at any time. However, this also causes the Worker to be more resource-intensive, should not be overused and should be shut down once used.

2, use,web workerWhat are the restrictions?

1. Same-origin restriction

The script file assigned to the worker must be the same as the main thread script file.

2. DOMlimit

The worker thread cannot read the DOM object of the page where the main thread resides. It cannot use the document, window, parent objects. Instead, it can use the Navigator and location objects.

3. Communication restrictions

Worker thread and main thread are no longer in the same context, cannot communicate directly, must be completed through messages.

4. Script restrictions

The worker thread cannot execute the alert and confirm methods, but it can make Ajax requests.

5. File restrictions

The worker thread cannot read the local file and cannot open the file system. The script to be loaded must come from the network and cannot be the file:// file.

3,workerHow does a thread listen for messages from the main thread? How is the message sent?workerHow is the thread closed?

The Worker thread needs to have an internal listening function that listens for message events.

/ / to monitor
self.addEventListener('message'.function (e) {
  // Send the message
  self.postMessage('You said: ' + e.data);
}, false);
Copy the code

Shut downworkerthread

1) The main thread is closedworkerthread

worker.terminate()

2)workerThread closed

self.close()

4,workerHow does the thread load other scripts?

importScript('scripts.js')
importScript('scripts1.js'.'scripts2.js')
Copy the code

5. Main thread andworkerThe threadAPI

The main thread workerthread
Worker.onerror: specifyerrorEvent listener function self.name:WorkerThe name of the
Worker.onmessage: specifymessageEvent listener function self.onmessage: specifymessageEvent listener function
Worker.onmessageerror: specifymessageerrorEvent listener function self.onmessageerror: specifymessageerrorEvent listener function
Worker.postMessage()To:WorkerThread sending message self.close()Closed:Workerthread
Worker.terminate(): Immediate terminationWorkerthread self.postMessage(): to produce thisWorkerThread sending message
self.importScripts()Loading:JSThe script

42,webSocket

1. WhywebSocket? What are the characteristics?

1. Advantages:

  1. Support two-way communication, more real-time;
  2. Better binary support;
  3. wsWhen the client and server exchange data, the packet header is smaller, which can better control the cost.
  4. Support expansion.

2. Features:

  1. Based on theTCPProtocol, the implementation of the server side is relatively easy.
  2. withHTTPThe protocol has good compatibility. The default ports are also 80 and 443, and the handshake phase is usedHTTPProtocol, so handshake is not easy to mask, can pass variousHTTPProxy server.
  3. The data format is relatively light, low performance overhead, and efficient communication.
  4. You can send text or binary data.
  5. Without the same origin restriction, the client can communicate with any server.
  6. The protocol identifier isws(If encryption is used, the value iswss), the server url isURL.

2,webSocketLink status?

  • 0 (WebSocket.CONNECTING)Linking
  • 1 (WebSocket.OPEN)Link and communication is available
  • 2 (WebSocket.CLOSING)Connection closing
  • 3 (WebSocket.CLOSED)The connection was closed or no connection was successful