What is a compiled language? What is interpreted language?JS
What 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.JS
What are the castings and implicit casts in the
1. Cast a type
String()
Number()
Boolean()
parseInt()
parseFloat()
2. Implicit type conversion
+ string
Converted to digitala + " "
Convert to string! var
Convert to a Boolean value
Basic data types and reference data types
1, the difference between
1. As an argument to a function:
- A primitive data type is passed a copy of the data, and changes to the original data do not affect the incoming data.
- 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:
- Basic data types are stored in the stack.
- 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
- Put this code in
Code Segment
; - The variable
a
In theStack: local variables and Pointers
; - will
{name: 'yuhua'}
In theHeapTotal: Object, closure
.
3,symbol
1. symbol
How do I get the key name of an object?
Can’t getsymbol
Key:
for in
与for of
You don’t get it in the loopsymbol
Key;Object.keys()
,Object.getOwnPropertyNames()
,JSON.stringify()
Method cannot getsymbol
Key;
Can getsymbol
Key:
Object.getOwnPropertySymbols()
Method can be fetched and returns an array;Reflect.ownKeys()
You can get all key names, includingsymbol
键
2. symbol
Type 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,null
和 undefined
The difference between
1.Null
null
Represents 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 + null
位5
2,Undefined
- The variable is declared, but not assigned, is equal to
undefined
; - When the function is called, the argument that should be provided is not provided, which is equal to
undefined
; - Object has no assignment property, which has a value of
undefined
; - Function returns no value by default
undefined
; Number(undefined)
为NaN
;5 + undefined
为NaN
.
Five,typeof
和 instanceof
The difference between
1. Major differences
typeof
Represents the detection of a variable type, except for the basic data typenull
Are normally displayed as their corresponding types, except for reference typesfunction
All the others will be displayed asobject
;instanceof
Test whether the stereotype object of a constructor is in the stereotype chain of an object.
2,typeof
对 null
Error 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 functionthis
When was it determined?
When a function is called, it points to the object that was last called
3,call
,apply
,bind
The 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?
- Default binding: in the global environment,
this
Default binding towindow
. - Implicit binding: Generally, when a function call is contained by a direct object, also called a method call,
this
Implicitly bind to the direct object. - Implicit loss: Implicit loss is when an implicitly bound function loses its binding object and thus defaults to
window
. Explicit binding: Passedcall()
,apply()
,bind()
Method to bind an object tothis
Is called explicit binding. new
Binding: If a function or method call is preceded by a keywordnew
, which constitutes a constructor call. forthis
For binding, theta is thetanew
Binding.
5. Arrow functionthis
- The arrow function is not there
this
, so you need to find the scope chain to determinethis
Which means that if the arrow function is contained by a non-arrow function,this
It’s bound to the nearest non-arrow functionthis
. - Arrow functions don’t have their own
arguments
Object, but can access peripheral functionsarguments
Object. - Can’t pass
new
Keyword call, again nonew.target
Values and prototypes.
6. Manual implementationcall
,apply
和 bind
?
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,this
Point 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,JS
modular
1, modular development history
IIFE
Self-executing functionAMD
userequireJS
To write modularity (dependencies must be declared in advance.)CMD
useseaJS
To write modularity (to support the dynamic introduction of dependency files.CommonJS
nodeJs
Modularity is built inUMD
Compatible withAMD
,CommonJS
grammarwebpack(require.ensure)
:webpack 2.x
Code segmentation in versionES Modules
:ES6
Introduced modularity, supportimport
Let’s introduce another onejs
script
The labeltype="module"
2,AMD
和 CMD
The 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
AMD
When defining a module, you must declare which module it depends onCMD
The nearest dependencies are recommended, only when a module is neededrequire
3,CommonJS
Characteristics of the specification
- So code runs in the module scope and does not contaminate the global scope
- Modules are loaded synchronously. The following operations are performed only after the imported modules are loaded
- The module is cached after the first execution, and reloading returns only the cached results
CommonJS
The 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 modules
What are the characteristics of the specification
- The output using
export
- Introduction to use
import
- You can use
export ... from ...
To achieve a transit effect - The input module variable is not reassigned. It’s just a readable reference, but the property can be overwritten
export
和import
The command is at the top level of the module, cannot be in scope, is in the code block, cannot do static optimization, violatedES6
The design of the moduleimport
If there is an improvement effect, it will be promoted to the head of the entire module, which is executed firstBabel
theexport/import
intoexports/require
So you can useexports
和import
5,CommonJS
和 ES6 Modules
Differences in specifications
CommonJS
Modules are loaded at runtime,ES6Modules
Is loaded at compile timeCommonJS
Copy of the output value,ES6Modules
References to output values (internal module changes affect references)CommonJS
The import module can be an expression (which is used byrequire()
The introduction of),ES6Modules
Imports can only be stringsCommonJS
Where this refers to the current module,ES6Modules
中this
Point to theundefined
ES6Modules
There is noarguments
,require
,module
,exports
,__filename
,__dirname
These 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?
- security
- closed
- Avoid variable conflict
- Isolation scope
- The withdrawal of common code
Eight,node require(X)
What is the processing order introduced?
- if
X
If it is a built-in module, this module is returned and the execution is not continued. - if
X
以'./', '/', '.. / '
The beginning will be based onX
Parent module, okX
The absolute path of: aX
If the file exists, return the file and do not continue the execution. B. willX
If 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. - if
X
Without a path: a. According toX
Parent module, okX
Possible installation directories b. In each directory in turn, willX
Load as filename or directory name - throw
not found
error
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
a.js
The script outputs one firstdone
Variable, and load another script fileb.js
. Notice that at this pointa.js
The code just sits there, waitingb.js
When you’re done, let’s move on.b.js
On the second line, it will loada.js
At this point, a “looping load” occurs. The system will go toa.js
Module of the corresponding objectexports
Property value, but becausea.js
It’s not done yet, sinceexports
Properties can only fetch the part that has been executed, not the final value.a.js
The part that has been executed has only one line.
exports.done = false;
Copy the code
- So, for
b.js
In terms of, it comes froma.js
Enter only one variabledone
And has a value offalse
. b.js
Then go down the execution, until all the execution is completed, then the execution power back toa.js
. As a result,a.js
Then 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
- The above code proves two things. One is in
b.js
,a.js
It’s not finished. Only the first line is executed. The second is,main.js
On 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,JS
The 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:
- Only bubbling events are supported, non-bubbling events cannot be brokered (
focus/blur
) - All events are agent prone to error, recommend nearby delegate
- Internal element hierarchy is too many, easy to be blocked by a layer
2,document
,window
,html
,body
The hierarchy of
window > document > html > body
window
是BOM
On 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;document
Is a document-related object that has some ability to manipulate the contents of the document;html
Elements anddocument
Element objects belong tohtml
The documentDOM
Object.
3,addEventListener
What’s the third argument to the function?
1. When toboolean
When:
- The third parameter involves whether to bubble or capture;
- for
true
Where is capture, isfalse
It is bubbling.
- for
2. When toObject
When:
capture
:Boolean
Said,listener
Is propagated to this during the event capture phase of this typeEventTarget
When triggered.once
:Boolean
Said,listener
It is called at most once after adding. If it istrue
.listener
Will be removed automatically after it is called.passive
:Boolean
, is set totrue
Said,listener
Never callpreventDefault()
. iflistener
If the function is still called, the client will ignore it and throw a console warning.mozSystemGroup
: only inXBL
Or is itFirefox' chrome
Use, this is aBoolean
Said,listener
Is 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
- use
Event
- use
customEvent
- use
document.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,JS
Internal 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?
- Using closures, you can access variables in a function;
- Variables can be kept in memory for a long time.
4. Memory leak
1. Memory leak:
- A circular reference
- Automatic boxing conversion
- Some of the
DOM
operation
(44. Closure
2. Memory leak solution:
- Below cast, which can be avoided by displaying cast;
- Avoid circular references caused by events;
- Dustbin operation;
- 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,EventLoop
Execution process of
1. BrieflyEventLoop
Execution process of
- The whole
script
Execute 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’s
UI
Thread rendering work; - Check whether there is
web worker
Task, 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.
- Called before rerendering.
- 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
50ms
It ensures that the user gets a response with an unconscious delay.
4,EventLoop
Circulatory 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.
requestAnimationFrame
Executed before re-rendering the screen, which is great for animating.requestIdleCallback
Execute 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 ittimeout
Parameters.resize
和scroll
The event actually has its own throttling, it only inEvent Loop
The render phase to dispatch events toEventTarget
On.
5,for
Circulation andsetTimeout
Add a setTimeout to the for loop
for (var i = 0; i < 10; i++) {
setTimeout(() = > {
console.log(i)
}, 1000)}Copy the code
1. var
tolet
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. for
Loop toforEach
cycle
[1.2.3.4].forEach(item= > {
setTimeout(() = > {
console.log(item)
}, 1000)})Copy the code
4. setTimeout
The 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,JS
In thelet
,const
,var
1.JS
How many ways are there to define variables in
let
const
var
class
import
function
2,let
,const
,var
What’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,const
Can defined constants be modified?
const
Defined base types are not modifiable;const
Defining a reference type allows you to modify the value within the reference type.
4. If I want toconst
What if defining a reference type doesn’t change its value?
Object.freeze
;- Agent (
proxy/Object.defineProperty
); - Modify an object’s
configurable
,writable
Properties.
5, how to inES5
Is implemented in the case oflet
和 const
?
1. The implementationlet
This can be done through self-executing functions.
2. Implementconst
You can set writable via object.defineProperty ().
Twelve,JS
An array of
1.ES6
New array method
Array.from(), array.of (), copyWithin(), find(), findIndex(), fill(), entries(), keys(), values(), includes().
2,ES5
New 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,some
和 every
What’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
- double
for
Cycle; - Recursive loop.
2. Use the syntax itself with keys that are not repeatable or API repeatable
ES6
Set
Go to the heavy;- Create an empty object to deduplicate;
- Single layer circulation +
filter/includes/indexOf
; - Single layer circulation +
Map
,Object
duplicate removal
7,for
Circulation andforEach
Which performance is better?
for
Loops perform better
for
Loop without any additional function call stack and context;forEach
Not ordinaryfor
The 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,sort
What 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
reduce
The recursive implementationjoin
和split
implementation- The recursive traversal
flat
methodstoString
和split
implementation- 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 vertices
v
; - In turn, from
v
The depth first traversal of the graph is carried out. Until the figure neutralizesv
All 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
,forEach
What 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 in
和 for of
What’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 0 key It is not traversable map/set You can’t iterate generators 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 0 value Can traverse map/set To iterate generators IE does not support |
The same | You can iterate through groups of numbers can break Interrupt traversal |
You can iterate through groups of numbers can break Interrupt traversal |
Fourteen,Promise
1. How to implement onesleep
Function (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,promise
Constructor,then
Methods,catch
Methods,finally
Which 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,promise
How do you achieve your first successpromise
?
Get the first successful Promise out of multiple promises
1. Promise.all
To 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,promise
And all thepromise
Returns the result regardless of success/failure.
1. Promise.all
To 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 aboutpromise
What 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.then
Do you know the second parameter of? and.catch
What’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.
then Second parameter |
catch |
---|---|
then Method parameters |
Promise Instance method of |
then The 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 isthen Method syntax sugar |
If the second argument is the sumcatch Co-existence,promise Internal error, second parameter can be captured |
At this point,catch No, the second parameter does not exist,catch To capture |
Not recommended | It is recommended to usecatch Error catching |
Eight,Promise.resolve
How many cases?
1. Parameter is onePromise
The instance
If the argument is a Promise instance, promise.resolve will return the instance intact, with no modifications.
2. Parameter is onethenable
object
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.then
Is 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.finally
Followed by a.then
, so thisthen
What 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
finally
Takes no arguments in the callback function of;- in
promise
At the end, whatever the result isfulfilled
Or is itrejected
, will be implementedfinally
Callback function; finally
It returns a previous onePromise
Object value.
11,.all
和 .race
Do 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,.all
Is it concurrent or serial?
Is concurrent, but the return value is in the same order as the array received in promise.all.
13,promise
Why 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)Generator
Functions 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.stringify
和 JSON.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
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
reviver
The converter, if passed, can be used to modify the original value generated by the parse.
features
- Convert value if there is
toJSON()
Method that defines what values will be serialized. - Properties of non-array objects are not guaranteed to appear in a serialized string in a particular order.
- Boolean, numeric, and string wrapper objects are automatically converted to their original values during serialization.
undefined
, any function andsymbol
Value, 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,undefined
When converted individually, returnsundefined
, such asJSON.stringify(function(){})
orJSON.stringify(undefined)
.- Executing this method on objects that contain circular references (objects that refer to each other in an infinite loop) throws an error.
- All to
symbol
Properties that are property keys are completely ignored, even if they are included in the replacer parameter. Date
The date is calledtoJSON()
Convert it tostring
String (same asDate.toISOString()
), so it is treated as a string.NaN
和Infinity
Format andnull
Will be treated asnull
.- Other types of objects include
Map/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 conversionObject.is(val1, val2)
Determine whether the two values are the same
2,= =
How is a type conversion done?
- If the type is different, the conversion is performed
- Determine whether the comparison is
null
Or is itundefined
If yes, returntrue
- Check whether the type is
string
ornumber
, if so, willstring
convertnumber
- Determine whether one of the parties is
boolean
If yes, convert one party to the othernumber
In judgment - Determine whether one of the parties is
object
And the other side isstring
,number
,symbol
, if so, willobject
Convert to primitive type for judgment (valueOf()
Methods) - If one of them is
NaN
Is returned directlyfalse
- If both are objects, the comparison points to the same object
3,[] = =! []
What is the value of?
Answer: true
The transformation steps
- ! Operator has the highest priority,
! []
Will be converted tofalse
, therefore, is[] == false
- According to article 4, one of the parties is
boolean
,boolean
tonumber
, so this is[] = = 0
- And then according to article 5, the array
[]
Convert to the original type and call the arraytoString()
Method,[].toString() = ''
, so this is' '= = 0
- And then according to the third rule, put
string
tonumber
.' '
tonumber
Theta is zero. So at this point0 = = 0
- The data types on both sides are the same
0 = = 0
fortrue
4, object.is () determines if two values are equal
Casts are not performed
- Are all
undefined
- Are all
null
- Are all
true
或false
- 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 all
0
- Are all
NaN
- Or both are nonzero and nonzero
NaN
And be the same value
- Are all
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
,sessionStorage
和localStorage
1, the difference between the three
cookie
Used to save login information. The size limit is4KB
Or solocalStorage
是Html5
Newly added, used for local data storage, saved data has no expiration time, general browser size is limited to5MB
sessionStorage
Interface methods andlocalStorage
Similar, 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 timeHTTP Header, if usedcookie Saving too much data can cause performance problems |
Generally not, the samedomain Can 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,localStorage
How 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:
- Agreement,
- The domain name
- 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?
ajxa
requestDom
The 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 (
ajax
Same-origin policy,Dom
Same-origin policy).
4. What are the cross-domain solutions?
CSDN cross-domain problem solved
jsonp
cors
postMessage
websocket
Node
Middleware broker (twice across domains)nginx
The reverse proxywindow.name + iframe
location.hash + iframe
document.domain + iframe
5,CORS
What are the common configurations?
Access-Control-Allow-Origin
Allowed domain namesAccess-Control-Allow-Methods
Allow thehttp
Request methodAccess-Control-Allow-Headers
Supported request headersAccess-Control-Allow-Credentials
Whether to sendcookie
Access-Control-Max-Age
Cache time in seconds
6,CORS
Cross-domain decision flow
- If yes, the browser sends data directly. Otherwise, the browser sends a cross-domain request.
- After receiving the cross-domain request, the server returns the corresponding file header according to its configuration.
- The browser receives a response based on the header
Access-Control-Allow-origin
Field. 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:
- use
get
,post
,head
One of the methods to make the request; http
Header 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 request
XMLHttpRequestUpload
The object does not register any event listeners; XMLHttpRequestUpload
Object can be usedXMLHttpRequest.upload
Property access. Not used in the requestReadableStream
Object.
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?
script
Tags, embedded cross-domain scripts;link
Tag, embedcss
;img
Tag, embedded image;video/audio
Tag, embedded video, audio;object/embed/applet
Tag, embedsvg
/ pictures, etc.;svg
Tag, embedsvg
;- through
@font-face
Embedded fonts; - through
iframe
Embedded 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, sayjs
Inheritance 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:
- Simple inheritance
- The parent class adds new methods, attributes, subclass can access
Disadvantages:
- Multiple inheritance is not possible
- All properties from the parent class are shared by all instances
- To add properties and methods to a subclass, you must add them after child.prototype = new Parent() because they will be overridden
- 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:
- The problem of subclass instances sharing parent class reference properties in prototype chain inheritance
- When you create a subclass instance, you can pass arguments to the parent class
- Can implement multiple inheritance (call multiple parent objects)
Disadvantages:
- An instance is not an instance of a parent class, just an instance of a child class
- Only instance properties and methods of the parent class can be inherited, not prototype properties and methods
- 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:
- You can inherit instance properties/methods as well as stereotype properties/methods
- There is no problem with reference attribute sharing
- Can pass the cords
Disadvantages:
- 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:
- The superclass constructor is not called twice
Disadvantages:
- 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 class
The 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:
- 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,ajax
的 readyState
The state of the
0
Uninitialized, not called yetopen()
methods1
Start, already calledopen()
Method, but not calledsend()
methods2
Send, already calledsend()
Method, but the response has not yet been received3
Received. Partial response data has been received4
Done. 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:
- from
node.js
createhttp
request - support
Promise API
- Client support for prevention
CSRF
- 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 standard
Promise
Implement, supportasync/await
- Isomorphism is convenient to use
isomorphic-fetch
2. The shortcomings
Fetch
The request defaults to nonecookie
, need to be setfetch(url, {credentials: 'include'})
- Not when the server returns a 400,500 error code
reject
When the request cannot be completed due to network errors,fetch
Will bereject
.
24,new
The operator
1.new
Implementation process of
- Create a new object;
- 2. Assign the scope of the constructor to the new object (thus
this
Refers 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 constructor
prototype
Associated 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
,WeakMap
和 set
,WeakSet
What’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 multiple
NaN
, 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,weakSet
role
- and
Set
Structure similar, member values can only be objects - storage
DOM
Nodes:DOM
This 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 remains
WeakSet
The references in the structure are automatically eliminated - Members are weak references and are not considered by garbage collection
WeakSet
Structure a reference to this member - Member is not suitable for reference, it will disappear at any time, so
ES6
provisionsWeakSet
The 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 exists
WeakSet
In 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 one
NaN
As a key, there will only be oneNaN
Value as a key Object
Structure provides the corresponding string – value,Map
The structure provides the value – the corresponding value
5,WeakMap
- and
Map
Similar structure, member keys can only be objects - storage
DOM
Nodes:DOM
This 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 collection
WeakMap
Structure a reference to this member key - The member key is not suitable for reference, it will disappear at any time, so
ES6
provisionsWeakMap
The 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 exists
WeakMap
In 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,Object
toMap
let obj = {"a":1."b":2};
let map = new Map(Object.entries(obj))
Copy the code
27,Proxy
1, grammar,
target
In order to useProxy
The wrapped target object (which can be any type of object, including a native array, a function, or even another proxy)handler
An 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,Handler
Object
methods | describe |
---|---|
handler.has() |
in Operator. |
handler.get() |
Property read operations. |
handler.set() |
Property set action. |
handler.deleteProperty() |
delete Operator. |
handler.ownKeys() |
Object.getOwnPropertyNames Methods andObject.getOwnPropertySymbols Method. |
handler.apply() |
A catcher for a function call operation. |
handler.construct() |
new Operator |
# # # 3,proxy Can an agent be revoked? |
|
proxy There’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} |
proxy
Represents 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.revoke
The 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:
- Create a global object. In the browser, the global object is
window
Object. - will
this
The 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. Eval
Function execution context:
The eval function of js creates its own execution context and is rarely used and not recommended.
2. Features of execution context
- Single thread;
- Synchronous execution, sequential execution from top to bottom;
- There is only one global context, namely
window
Object; - There is no limit to the number of function execution contexts;
- 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
- Create a variable object: First initialize the parameters of the function
arguments
To promote function declarations and variable declarations. - 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,
JavaScript
Always 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. - determine
this
Point to: determinethis
Pointing to.
2. Execution phase
- Perform variable assignment.
- Function references.
- Execute other code.
3. Recycle
- Execute context off stack
- Wait for the VM to reclaim the execution context
4,js
How 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,setTimeout
implementationsetInterval
; (() = > {
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 generationexcel
Form 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.prototype
So 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,js
Garbage collection (GC
)
1.V8
Memory limit
- The 64-bit system has 1.4 GB of memory available
- The 32-bit system has 0.7 GB of memory available
2,V8
Memory management
JS
Objects are all passedV8
To allocate and manage memoryprocess.memoryUsage()
Returns an object containingNode
Memory 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 variable
a
In the stack (Stack
) : local variable, pointer” - will
{name: "yuhua"}
In the”HeapTotal
(Heap) : Object, closure”
- Put this code in the “code area”
- Note: The basic data types are in the stack, and the reference types are in the heap
4. Why limit memory size
- because
V8
Because 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) becomes
Stop The World
During this period, the performance and responsiveness of the application will degrade
5,V8
Garbage collection mechanism
V8
Is 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 by
From
Regional andTo
Region Consists of two regions - On 64-bit systems, the new generation of memory is 32 megabytes,
From
Regional andTo
Each area occupies 16M - In 32-bit systems, the new generation of memory is 16 megabytes,
From
Regional andTo
Each 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 adoptsScavenge
algorithm
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 check
FROM
The surviving objects in the region, if still alive, are copied toTO
Space to clear (free) after all living objects have been copied.FROM
area - 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
TO
More than 25% of the space used, or oversized objects- The browser
memory
You can take a snapshot to see if the variable is garbage collected - Set to
undefined
或null
Can subtract 1 from the reference count
8, the old generation adoptedMark-Sweep
和 Mark-Compact
1. The basic
- There are two types of old generation garbage collection strategies
mark-sweep
Mark 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-compact
Tag 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,
GC
It takes a long time - in
GC
I can’t listen to it,STOP-THE-WORLD
V8
One 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-Sweep
Mode 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-Compact
Mode 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 |
V8
It is mainly used in the old generationsMark-Sweep
Because theMark-Compact
Objects 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:
- Performance rating and salary calculation bonus is
- 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 browser
window
Object. inJavaScript
In 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
- Unlike a function declaration, a function name is valid only within the function, and the binding is a constant binding.
- Assign to a constant at
strict
An error is reported in modestrict
Silent failure in mode. IIFE
The functions in are function expressions, not function declarations.
2. Function type
- Function declaration
- Function expression
- Function constructor is created
1. Function declaration (FD
)
- There’s a particular name for it
- Location in the source code: either at the program level (
Program level
), or in the body of another function (FunctionBody
) - Created during the enter context phase
- Influence variable object
- Declare it as follows
function funName () {}
Copy the code
2. Function expression (FE
)
- Must appear in the source code at the position of the expression
- There are optional names
- Does not affect variable objects
- 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
- Create an object
- 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,XSS
Attacks andCSRF
attack
1.XSS
attack
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
- Coding; Encode user input.
- Filtering; Removes attributes associated with user input and events. (filter
script
,style
,iframe
Such as node) - Correction; use
DOM Parse
Convert, correct for unpairedDOM
The label. 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 the
DOM
: Malicious modificationDOM
Structure, based on client
2,CSRF
attack
1. The concept
Cross-site request forgery (SRF) : Cross-site request forgery.
Principle 2.
- Log on to trusted sites
A
And is generated locallyCookie
. (If the user is not logged in to the siteA
, then the websiteB
During induction, request the siteA
的api
Interface, will prompt you to log in). - Without logout
A
In case of visiting dangerous websitesB
(Actually use the websiteA
).
3. To prevent
token
Validation;- Hide the token; the
token
Hidden in thehttp
The request ofhead
In the. referer
Validation; Verify the source of the page.
3. Differences between the two
CSRF
: Requires the user to log in to the websiteA
To obtaincookie
.XSS
: No login is required.CSRF
: is to use the websiteA
The bug itself, go to the request websiteA
的api
.XSS
: is to the websiteA
injectionJS
Code, and then executeJS
To tamper with the siteA
The content of the.
36,input
Input 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:
ajax
:abort()
axios
:CancelToken
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,750
The width,1rem = 100px
.iphone6/7/8 plus
Set in theWidth: 6.5 rem
What 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
as
Value including
script
style
image
media
document
onload
A method is a callback function that completes resource loading
4,defer
和 async
//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
- parsing
HTML
To generate theDOM
树 - parsing
CSS
To generate theCSSOM
树 - will
DOM
Trees andCSSOM
Tree 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 nodePainting
(redraw) : Obtain the absolute pixels of a node based on the geometric information obtained from the rendered tree and backflowDisplay
: sends pixels toGPU
Is displayed on the page. (This step is actually a lot of content, such as inGPU
Combine multiple composition layers into a single layer and display it on a page. whilecss3
Hardware acceleration works by creating a new composition layer.)
2. When to trigger backflow and redraw
1. Return
- Add or remove visible
DOM
The 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
,visibility
Etc.), 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 of
table
Layout. - As far as possible in
DOM
The end of the tree changesclass
. - Avoid setting multiple inline styles.
- Apply the animation effect to
position
Properties forabsolute
或fixed
On the elements of - Avoid the use of
CSS
Expressions (e.g.calc()
) CSS3
Hardware acceleration (GPU
Acceleration)transform
opacity
filters
Will-change
2. JavaScript
- Avoid frequent manipulation of styles. It is better to rewrite them all at once
style
Property, or define the style list asclass
And change it onceclass
Property, modifystyle
的cssText
Attribute or modify the elementclassName
Value. - Avoid frequent operations
DOM
, create adocumentFragment
, apply allDOM
Action, and finally add it to the document - You can also set it for the element first
display: none
And then display it after the operation is over. Because in thedisplay
Properties fornone
On the elements ofDOM
Operation 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.
- use
css3
Hardware acceleration can allowtransform
,opacity
,filters
These animations do not cause a backflow redraw. But for other properties of the animation, such asbackground-color
These 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?
3D
orCSS transform
<video>
和<canvas>
The labelCSS filters
- Element, such as using
z-index
attribute
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. if
GPU
With 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. - use
GPU
Rendering affects the anti-aliasing effect of fonts. This is becauseGPU
和CPU
There 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,H5
和 native
The 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 systemapi Rich, can achieve more functions, better experience |
portability | Compatible across platforms, such asPC With the mobile terminal,iOS 与 Android |
Low portability foriOS 和 Android Two sets of code need to be maintained |
# # # 3,JSBridge The purpose of the |
||
JSBridge As in the name”Bridge “Is the same as” isNative And theNative Between the bridge, its core is to buildNative And theNative A channel for message communication between two – way communication. |
||
2. A two-way communication channel: |
JS
向Native
Sending messages: calling related functions and notificationsNative
The currentJS
And so on.Native
向JS
Send messages: trace back call results, message push, notificationJS
The currentNative
And so on.
4,JSBridge
process
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 one
Native
与JS
Global bridge object for interaction - The second step:
JS
How to callNative
- Step 3:
Native
How to learnapi
Is called - Step 4: Analyze
url-
Parameter and callback format - Step 5:
Native
How to callJS
- Step 6:
H5
中api
Method registration and format
5,JSBridge
The realization principle of
JavaScript
callNative
Injection is recommendedAPI
The way (iOS6
Ignore,The Android 4.2
Use the followingWebViewClient
的onJsPrompt
Way).Native
callJavaScript
The spliced command is executed directlyJavaScript
Code.
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. Native
调 JS
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. JS
调 Native
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,JSBridge
Interface 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 callNative
When the functionCallback
How 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,JSBridge
How to reference
By 1.Native
End 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.JavaScript
The 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 worker
What 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. DOM
limit
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,worker
How does a thread listen for messages from the main thread? How is the message sent?worker
How 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 downworker
thread
1) The main thread is closedworker
thread
worker.terminate()
2)worker
Thread closed
self.close()
4,worker
How does the thread load other scripts?
importScript('scripts.js')
importScript('scripts1.js'.'scripts2.js')
Copy the code
5. Main thread andworker
The threadAPI
The main thread | worker thread |
---|---|
Worker.onerror : specifyerror Event listener function |
self.name :Worker The name of the |
Worker.onmessage : specifymessage Event listener function |
self.onmessage : specifymessage Event listener function |
Worker.onmessageerror : specifymessageerror Event listener function |
self.onmessageerror : specifymessageerror Event listener function |
Worker.postMessage() To:Worker Thread sending message |
self.close() Closed:Worker thread |
Worker.terminate() : Immediate terminationWorker thread |
self.postMessage() : to produce thisWorker Thread sending message |
self.importScripts() Loading:JS The script |
42,webSocket
1. WhywebSocket
? What are the characteristics?
1. Advantages:
- Support two-way communication, more real-time;
- Better binary support;
ws
When the client and server exchange data, the packet header is smaller, which can better control the cost.- Support expansion.
2. Features:
- Based on the
TCP
Protocol, the implementation of the server side is relatively easy. - with
HTTP
The protocol has good compatibility. The default ports are also 80 and 443, and the handshake phase is usedHTTP
Protocol, so handshake is not easy to mask, can pass variousHTTP
Proxy server. - The data format is relatively light, low performance overhead, and efficient communication.
- You can send text or binary data.
- Without the same origin restriction, the client can communicate with any server.
- The protocol identifier is
ws
(If encryption is used, the value iswss
), the server url isURL
.
2,webSocket
Link status?
0 (WebSocket.CONNECTING)
Linking1 (WebSocket.OPEN)
Link and communication is available2 (WebSocket.CLOSING)
Connection closing3 (WebSocket.CLOSED)
The connection was closed or no connection was successful