js notes

js notes

Know the browser

  1. The part that the user can operate is called the shell outer core mainstream browser core IE trident Chrome webkit/blink firefox Gecko Opera presto
  2. The part that the browser cannot display is called the kernel rendering engine: html css syntax recognition drawing js engine: other modules
  3. Google browser v8 engine developed in 2008: the fastest translation of js code into mechanical code
  4. The browser is multi-threaded: 1. js engine 2. UI engine 3. event thread 4. request thread 5. timer thread

js start

1. Features:

  1. Interpretative language, no special files are generated and directly translated and executed by the machine. <> are all interpreted languages
    1. Advantages: cross-platform
    2. Disadvantages: slightly slower
  2. Single thread

2. Execution queue:

Rotate time slices, split tasks into time slices, arrange them randomly, and send them to the engine for execution

Three.js three major parts

  • ECMAScript
  • DOM
  • BOM

How to introduce js both externally and internally exist and only execute externally

In-page < script > </script > copy code
Introducing the outside < Script the src = "location.js" > </Script > copy the code

Variables and data types

1. Variable : used to store data, to facilitate subsequent use

var a; declare variables (open up memory space) //a: space name a=100;//assignment: put 100 into the space a//naming rule: the beginning must be -> underscore_ letter $ in the middle -> underscore_ Key words and reserved words cannot be used for letters $ and numbers. Copy code

2. Data Types

  • Original value: Unchangeable, but the variable is reopened. Number (born as a floating-point type) Boolean String undefined null stack The advanced stack comes out at the end. The pocket stack and the stack assignment are copied and do not affect each other.

  • Reference value: array Object function

var ARR = [ . 1 , 2 , . 3 ] copy the code

The heap name is stored in the stack (pointer) -> the content is stored in the heap (address) and the name points to the address

  1. Grammar: Use at the end of each sentence; the end tells the program that the end of this sentence {} does not need to be developed, and there must be a space on both sides of any symbol

    var a = 1 ; copy the code
  2. Syntax error in a block of error does not affect other code blocks

    1. Error 1: grammatical analysis error (low-level error) When scanning the whole, you will find that a line of code will not be executed
    2. Error 2: Logic error (standard error) Start to execute the js code to the error line, it will stop reporting
  3. Operator 1. Mathematical operations, string concatenation

    Copy code

var a="aa"+"aa"; => aaaa//string

2. Any data type plus string is equal to string ```javascript var a="aa"+1 = aa1//string Copy code

Operator

Comparison operator : the result is only false true only NaN is not equal to NaN, the reference data type is not equal to itself, and everything else is equal to itself

undefined == undefined //{} to true to false//== {} [] == [] == null////falsenull to true copy the code

&& (logical AND)

  • First look at whether the first expression converted to a Boolean value is true,

  • If it is true then it will look at the result of converting the second expression to a boolean value,

  • If there are only two expressions, only the second expression is seen, and the value of that expression is returned.

  • If a certain one is converted to boolean to false, then the value of that one is returned directly, without looking at the following 1. Common usage

    var n-= . 1 && 0 ; Document .write (n-); //0 copy the code

    2.Imitate the if statement

    2 > 1 && document .write( "aa" ); //Judging the copy code by the expression on the left
undefined null NaN3 "" 0 flase => false ; only six values are false copy the code

& Binary AND operation

|| (or) returns when it encounters true (the result after conversion to boolean value), and if it encounters false, it continues to be true, and all false is false

! (Not) Convert to Boolean and then negate

, First calculate the result on the left, then calculate the result on the right, and return the result on the right

Logical statement (if else)

if statement

IF (condition) {statement} execute copy the code

for loop

( 1 ) ( 2 ) ( 3 ) for ( var i = 0 ;i < 10 ; i++ ){ document .write( 'a' );} //Enter for and execute (1)//and then execute 2 for judgment//If successful, execute (3), execute the content of the loop body, and end the loop if it is unsuccessful. Copy the code

Actual execution order: 1.var i=0; 2.if(i<10){ document.write('a');} 3.i++ -> i=1; 4.if(){} 5.i++

The for loop can use condition one or three flexibly without writing in parentheses, but condition two must be written inside

var I = 100 ; for (; i--;) {documen.write ( "I")} copy the code

do while execute first and then judge

do {text + = "<br> number of" + I; I ++;} the while (I < . 5 ); duplicated code

switch usage

var n = 'a' ; switch (n){ case'a ' : console .log( 'a' ); //If there is no break after entering a case, it will continue to enter each case break; case '1 ': console.log (' b ') ; case' 2 ': console.log (' c ');} copy the code

Break usage: interrupt the operation of this layer (only one layer of loop can be jumped out)

var i = 100 ; for ( let k = 0 ;k< 999 ;k++{ for (;i--; ){ documen.write("i") if (i<= 0 ){ break //When it is 0 but when ends the outer loop will execute}}} copy the code

continue: Abort this operation and start subsequent operations

var I = 100 ; for (; i--;) {documen.write ( "I") IF (I <= 0 ) { Continue //cycle terminates when the cycle continues}} copy the code

Object

The object of js is different from the object of other languages, you can modify the object day after day, while other languages are basically hard-coded and cannot be modified

Object: Put together some data with common characteristics as an object

var mrdeng = { name : "deng" , age : 50 , sex : "male" , smoke : function () { Console .log ( "the I AM smoking" );}} copy the code

Object creation

1.plainObject object literal/object direct value assignment creation

var obj={ } Copy code

2. Constructor 1. The system's built-in constructor Object() -> var obj = new Object(); is equal to the first method. 2. Custom//Must conform to the big hump naming rule TheFirstName

function Person () {} Var Person = new new the Person (); duplicated code

Object properties CRUD (properties of the object call does not exist and does not complain, will report undefined)

mrdeng.health = "100" //Increase the object attribute mrdeng.name="gao"//Modify the object attribute and re-assign the value console.log(mrdeng.name);//Call the object attribute directly to delete mrdeng.name;//delete object properties copy the code

The internal principle of the constructor

Only when the new method is encountered will the operation create this object

function Student ( name, age, sex ) {step 1 //var this = {} Implicitly add this = {} to the front of the function body to create a theoretically empty object step 2//Write the properties of the constructor as written the sequence of this empty object attribute into this.name = name; this.age = age; this.sex = sex; this.grade = 2017; step 3//return this; } out this return this duplicated code

Iterate over objects

Object attribute access rules a. xx. Attribute name general usage b. xx['xx'] System access rules The system will convert to xx.['attribute name'] when accessing xx. name:'gao'} test.name === test.['name']

Object traversal (enumeration) method (for in)

@ Disadvantages: properties of the object will be taken out of the prototype, the prototype system are not removed provided, add themselves to the prototype Object attributes are taken for (var xx in obj) { } copy the code
for ( var XX (with a key attribute name of the object is stored) in obj (need to traverse the object)) {} copy the code
var obj = { name : 'qugao' , sex : 'male' , age : 10 , height : 100 } var prop; for (prop in obj){ //console.log(obj.prop);//output undefined because System conversion obj.prop---->obj.['prop'] put the prop in the string to access the prop attribute//prop accepts the property name of the object at this time is already a string without quotation marks console.log(obj[ prop]); } Copy code

hasOwnProperty

Determine whether it is a prototype, so that the for in loop does not go directly to the attribute value of the prototype

var obj = { name : 'qugao' , sex : 'male' , age : 10 , height : 100 , _proto_ :{ lastName : 'gao' }} for ( var key in obj) { if (obj.hasOwnProperty(key) ) { Console .log (obj [Key]);}} copy the code

in operation

Determine whether the object can access the property//Prototype property is also considered

Format: XX in obj

var Test = { name : 'qugao' } Console .log ( 'name' in Test) //to true copy the code

instanceof

Is there a prototype of B on the prototype of the A object?

A instanceof B

[] The instanceof the Array ; //truevar Test = {}; Test the instanceof Object;//to true copy the code

Object cloning

Shallow clone object

var obj = { name : 'abc' , sex : 'male' , age : 23 } var obj1 = {} function clone ( origin, target ) { var target = target || {} for ( var prop in obj){ target [prop] = origin[prop];} return target;clone(obj,obj1); Copy code

Deep cloning

var obj = { name : 'abc' , age : 123 , card : [ 'visa' , 'master' ], wife : { name : "bcd" , son : { name : "aaa" } }} var obj1 = { }deepClone(obj,obj1); function deepClone ( origin, target ) { var target = target || {}, toStr = "[Object Array]" ; for ( var Object .prototype.toString, arrStr = prop in origin){ if (origin.hasOwnProperty(prop)){ if (origin[prop] !== "null" && typeof (origin[prop]) == 'object' ){ if (toStr.call(origin[prop]) == arrStr){ target[prop] = [];} else {target[prop] = {};} //Here you can use the ternary operator to simplify: target[prop] = (toStr.call(origin[prop]) == arrStr)? []: {} deepClone(origin[prop],target[prop]); } else {target [prop] = origin [prop];}}} return target;} copy the code

Array

The array index starts from 0

var arr=[ 1 , 2 , 3 , 4 , "acv" , undefined ]; //standard notation a[0] 0th of the array arr.length//length of the array (length is the property of the array, you can get the length) copy Code

Array -> is a special object 1. Declaration definition a. Literal declaration

var ARR = [ . 1 , 2 , . 3 , . 4 ] copy the code

b. Constructor Example 1: var arr1 = new Array(10) -> Pass only one parameter will only specify the length, the value is empty Example 2: var arr2 = new Array(10,3) -> pass multiple Parameter setting the value of the array 2. Array reading and writing a.js array will not report the array out of bounds overflow, because the js array is based on the object, the object without this property will report undefined b. It can overflow and write, which is equivalent to new Enhancement

Array method

Do not change the original array

concat(); Concatenate two or more arrays Return a copy of the concatenated array (new array) Array concatenation

var a1 = [ 1 , 2 , 3 ]; var a2 = [ 3 , 4 , 5 ]; var a3 = a1.concat(a2); //a3 ->[1,2,3,4,5,6] Copy code

join(); Put all the elements in the array into a string join method The string in the parentheses is the delimiter

var A1 = [ . 1 , 2 , . 3 ]; var A3 = a1.join (separator); //A3 -> "l, 2,3"; duplicated code

slice();
Writing one: array.slice(start subscript); Take all elements from the beginning of the subscript (including subscript) Writing two: array.slice(start subscript, end subscript); Take from the beginning Between the subscript (including the start subscript) and the end subscript (not including the end subscript)

var a1 = [ 0 , 1 , 2 , 3 ]; var a2 = a1.slice( 1 ); //a2 -> [1,2,3]var a1 = [0,1,2,3]; var a2 = a1.slice(1,2);//a2 -> [1] Copy code

toString(); No parameters are required to convert an array to a string

var A1 = [ . 1 , 2 , . 3 ]; var A2 = a1.toString (); //A2 -> "l, 2,3" copy the code

Change the original array

pop(); Delete the last element of the array. If the array is empty, the array will not be changed and return undefined. Normal delete will return the deleted element.

var A1 = [ . 1 , 2 , . 3 ]; var A2 = a1.pop (); //A2 ->. 3 duplicated code

push(); Add one or more elements to the end of the array and return the length of the new array

var A1 = [ . 1 , 2 , . 3 ]; var A2 = a1.push ( . 4 ); //A2 ->. 4 copy the code

reverse(); Reverse the order of the elements in the array and return the array

var A1 = [ . 1 , 2 , . 3 ]; var A2 = a1.reverse (); //A2 -> [3,2,1] duplicated code

shift(); delete the first element of the array, if the array is empty, do not delete any, return undefined, normal delete returns the deleted element

var A1 = [ . 1 , 2 , . 3 ]; var A2 = a1.shift (); //A2 -> 2 copy the code

unshift(); Add an element to the front of the array and return the added length

var A1 = [ . 1 , 2 , . 3 ]; var A2 = a1.unshift (); //A2 ->. 4 copy the code

sort(); Sort the array and return the array in ascending order by default (small to large). The sort method leaves the programmer with a custom-defined interface. You can write a function in the sort method to return the return value to specify Ascending or descending

var a1 = [ 1 , 4 , 5 , 2 , 3 ]; var a2 = a1.sort(); //a2 -> [1,2,3,4,5]//(Descending order) var a1 = [1 , 4,5,2,3]; var a2 = a1.sort (function (a, b) {return a <b 1: -1?}); duplicated code

splice(); Writing method one: array.splice (specify subscript); format array.splice (start from the first number (required), how much length to intercept (required), add new elements at the cut (optional) ); Return to the snippet after interception

var a1 = [ 1 , 4 , 5 , 2 , 3 ]; var a2 = a1.splice( 1 ); //[4,5,2,3] intercept all starting from the first position//var a1 = [ 1,4,5,2,3]; var a2 = a1.splice ( 1,3);//[4,5,2] taken from a start retained three duplicated code

Packaging

  1. The original value cannot have attributes and methods
  2. new Number (digital original value) new String (string original value) new Boolean (Boolean type original value)
  3. What is the original value can use len|length
var str = "123" ; console .log(str.length); //The system will not report an error after detection, but creates a string object through new String(), then calls the length method, and then deletes the character String object copy code

Modify the length of the string

var str = 'abcd' ;str.length = 2 ; //=>What changes is the property of the string object cannot change the length of str console.log(str);//abcdconsole.log(str.length);//4 copy the code

Explicit data conversion

Number ();-> convert a number string to a number type, if it is not a number string, NaNNumber (" 123 "); -> 123 number type Number ("12a"); ->NaNNumber( undefined ); ->NaNNumber ( null ); -> 0 copy the code

parseInt(); Judging from the beginning, if it is a number, it will be retained, if it is not a number or a decimal point, it will be interrupted to retain the previous number. If it is a decimal point, it will find the number after the decimal point, and it will be interrupted when it is not a number. 1. Convert to an integer

the parseInt ( "123 aa" ); -> 123 numeric type the parseInt ( "1a23aa" ); -> . 1 numeric type the parseInt ( "a1a23aa" ); -> NaN3 copy the code

2. Convert to other bases

parseInt ( " 123 ", 2 ( 2 - 36 )); //The other binary to decimal parseFloat ();//and paserInt similar, into a floating-point type String ();//will be converted to characters of all types String type Boolean();//Convert all types to Boolean toString();//Convert the properties of the called variable to string type//undefined null can t be used//Convert numbers to hexadecimal var demo=10;var demo1=demo.toSting(8 (target base, convert to target base based on decimal)); copy the code

Implicit type conversion

1 + 1 = 21 + '1' = '11' 1 /'1' = 11 * "1" = 11 + [] = 11/[] = Infinity1 * [] = 01- [] = 11- {} = = {} + NAN1 ". 1 [Object Object]" . 1 *} = { NaN3 ! {} //to false! [] to false// copy the code

isNaN(); first put the variable in Number(); -> then compare with NaN++/-- +/-(positive and negative) -> first call Number() to convert and then ++ +/- -> as long as If one side is a string, call String() to convert to string type *|/-> first call Number() method to convert and then multiply && ||! -> implicitly call boolean method to determine
== != -> There is also type conversion undefined == null undefined is not greater than, not less than, not equal to 0 NaN!=NaN

===! ==->Absolutely equal to and not equal to no type conversion

Type judgment

typeof

Judge the data type, the return value is a string

  • Both null and array are objects
  • Array is function
  • Basic data type number boolean string object function undefined
typeof null //"Object" typeof []//"Object" typeof the Array (the Array constructor)//"function" typeof 1//"number" typeof false//"boolean" copy the code

If the variable is not defined, the output will report an error, but if it is placed in typeof, it will not report an error. typeof a -> returns an undefined but it is a string type

typeof A //undefined copy the code

Object.prototype.toString.call

The construction type judgment is printed by the tostring method of the construction class, all construction classes are based on the Object constructor

Object .prototype.toString.call( 999 ) //"[object Number]"Object.prototype.toString.call('')//"[object String]"Object.prototype.toString.call(Symbol())//"[object Symbol]"Object.prototype.toString.call(42n)//"[object BigInt]"Object.prototype.toString.call(null)//"[object Null]"Object.prototype.toString.call (undefined)//"[object undefined ]" Object.prototype.toString.call (true)//"[object Boolean] duplicated code
Object .prototype.toString.call({ a : 1 }) //"[object Object]"Object.prototype.toString.call([1,2])//"[object Array]"Object.prototype.toString. call (new Date)//"[ object Date]" Object.prototype.toString.call (function () {})//"[object function]" copy Code

obj instanceof Object

You can put the content you want to judge on the left and the type on the right to judge the JS type

Can only be used to determine complex data types, because instanceof is used to detect the constructor (on the right)

prototype
Whether the property appears on the prototype chain of an instance object (left)

[ . 1 , 2 ] the instanceof the Array //to true (function () {})//Function to true the instanceof ({A:}. 1) the instanceof Object to true//(new new a Date) to true//the instanceof a Date duplicated code

constructor

Searching through the prototype chain can be used to find objects and ordinary data, which is more accurate than instanceof and typeof

var x = [] var y = {} var z = Date () var a = 'aaa' console .log(x.constructor== Object ) //false Here the array is not recognized as an object console.log(x .constructor==Array)//trueconsole.log(y.constructor==Object)//trueconsole.log(a.constructor==String)//true string can be recognized normally console.log(z.constructor== Object)//false time is identified as the object is not an object console.log (z.constructor == Date)//true copy the code

Ternary operator

Equivalent to if else plus return format:
conditional judgment? Yes: No (and will return a value)

var NUM = . 1 > 0 ? 2 + 2 : . 1 + . 1 ; //4 returns duplicated code

function

Function declaration

//Standard function declaration function test(){}//The expression will ignore the function name (abc), which is equivalent to the anonymous function var test = function abc(){}//demo.name -> demo The standard syntax of the function expression is only The function expression can be executed symbolically, and the function expression executed symbolically becomes an immediate execution function var demo = function(){}//()->execution symbol//This becomes an immediate execution function var demo= function()()(); Copy code

formation

Function name must Parameter optional

If the number of parameters does not match, it will be matched in order. Regardless of whether there is a formal parameter reception, the system will generate a list of arguments (array). The received formal parameters and arguments have a mapping relationship. One changes the value and the other will follow the change, but the actual parameter list If you don t have it, you won t change it, you won t add it

Example: 1 function test ( a ) { //a formal parameter//parameter is equivalent to implicitly defining a variable var a;} test(1)//actual parameter 1; 2 function test(a,b){//arguments -> [2] a=2; console.log(arguments[0]);//2 b=2; console.log(b);//2 console.log(arguments[1]);//undefined} test (2); return copy the code

Function scope

The inside of a single scope can access the outside, but the outside cannot access the inside. 1. Global variables: Variables defined in the entire script tag. 2. Function variables: Variables defined in the function. Explanation of Function Scope Every Javascript function is an object. We can access some properties of the object, but some are not. These objects are only accessible to the Javascript engine. [[scope]] is one of them. [[scope]] attribute -> refers to what we call scope, which stores a collection of runtime contexts. (Create execution context in pre-compilation stage >AO object)

Generate scope and add scope. Global functions and variables are generated when they are defined. The scope generated points to GO. The scope generated when the global function is executed points to the current function. The AO object generated by the current function is placed at the top of the scope chain, and then the GO object is placed in the second part of the scope. The scope generated when the function and variable are defined will first copy the parent's scope local variable and function, when the function is executed, the AO object generated by itself will be placed at the top of the scope, and the copied scope chain will be moved downward.

function a () { function b () { function c () {} c();} b();}a();a defines defined a.[[scope]] --> 0 : GOa executes doing a.[[scope]] --> 0 :aAO 1 : GOb defined b.[[scope]] --> 0 :aAO 1 :GOb doing b.[[scope]] --> 0 :bAO 1 :aAO 2 :Goc defined c.[[scope]] --> 0 : bAO . 1 : AAO 2 : GOC doing C [[scope]] ->. 0 : CaO . 1 : bAO 2. AAO . 3 : Go copy the code

Destruction of scope When a function is executed, the top point of the scopechain will be destroyed, and it will return to the link when it was defined. When it is executed again, it will re-point to a unique execution context.

Function scope instance

var bb = 1 ; function aa ( bb ) {bb = 2 ; alrt(bb);};aa(bb);alrt(bb); //2 1//The function parameter is equal to the local variable of the function content, if value is modified not override the global value of the same name duplicated code

Recursion

(The complexity of time and space is relatively high and not practical) 1. Law: Put it on return 2. Exit: Known conditions Example: factorial

var num = parseInt ( window .prompt ("input the factorial required")); function test ( num ) { if (num== 0 ||num== 1 ){ return 1 ;} return num*test(num- 1 ); -> The layer call itself encounters an exit and then returns} Copy code

Js running process (compilation)

1. Syntax analysis is executed throughout, scanning for low-level grammatical errors 2. Pre-compilation -> Generate execution context objects (AO, GO) 3. Interpretation and execution

window object

imply global->imply global imply global variable >1. If any variable is assigned without declaration, this variable will be owned by the global object (window object) a=10;->window.a=10; (even if assigned Variables not included by var at the time are global variables owned by window by default) Example: function test() {var a=b= 123; } b-> global variables

2. All global variables are declared window properties of the object window is global var A = 10 ; -> window { A : 10 ;} -> window II.A = 10 ; duplicated code

Function precompilation

The pre-compilation process occurs just before the function is executed

function fn ( a ) { //AO{a:function a(){},b:undefined,d:funciton d(){}} console.log(a);//->function a(){} var a=123;//AO{a:123} console.log(a);//->123 function a() {}//Function declaration The declaration here has been prompted to the top of the function, and the console will not be declared again. log(a);//->123 var b = function () {}//Function expression AO{b:function (){}} console.log(b);//->function (){} function d() ())fn(1); Copy code

(A unique AO object will be created every time a function is executed, multiple calls will be created multiple times, and the function will be destroyed immediately after execution)

1. Create an AO object (activation Object) -> execution context AO{} 2. Find the formal parameter and variable declarations, and use the formal parameter name and variable name as the property name of the AO object, the value is undefined AO{a:undefined, b: undefined} 3. Unify the actual and formal parameters AO{a:1, b:undefined} 4. Find the function declaration in the function body, and assign the value to the function body

AO {a: function a () {}, b: undefined, d: function d () {}} copy the code

Global precompilation

var a = 123 ; //GO{a:123}function a(){}//123console.log(a);//1. Generate a GO object Global Object (GO===window)GO{ }//2. Find the variable declaration, the value is undefined GO{ a:undefined}//3. Find the function declaration, and assign the value to the function body GO{a: function a() {}}//4. Perform the assignment operation of a = 123 Go {a:123} Copy code

Logical summary

  1. First create variables based on var x and mount them on the OA object to form {x:undefined}
  2. Find if there is a function, if so, perform function assignment first (x:fnA)
  3. Then if there is an assignment operation of x ='xxx', the assignment operation will be performed to overwrite the previous variable, {x ='xxx')

Closure

The internal function is saved to the outside (because the point of its own scope has not been destroyed, it is still possible to access the saved scope point)

function a () { function b () { var bbb = 234 ; console .log(aaa);} var aaa = 123 ; return b;} var glob = 100 ; var demo = a(); //demo=bdemo();//b()//scope-> 0: bAO, 1 : aAO {aaa: 123}, 2: GO copy the code

1.a doing -> 0:aAO 1:GO 2.b defined ->0:aAO 1:GO The method a is executed and the point of scope 0 is destroyed, but the function name of b is returned and the scope of b is still pointing to aAO , You can also use aAO, so you can use aAO at will if you use b later

Disadvantages: the original scope chain will not be released, causing memory leaks (occupying memory).

Implementation

1. Example of realizing common variables: accumulator

function Foo () { var i = 0 ; return function () { console .log(i++); }) var f1 = Foo(), f2 = Foo(); f1(); f1(); f2(); //The parent function used in the function pointed to by each closure attributes are unique independent and will not be repeated and the cover duplicated code

2. Implement caching

function eater () { var food = "" ; var obj = { eat : function () { console .log( "i am eat" + "" +food); food = "" ; }, push : function ( myFood ) {food = myFood;}} return obj;} var eater1 = eater();eater1 .push( 'banana' );eater1.eat(); Copy code

3. Property privatization

Example: function Deng () { //Under normal circumstances, the property cannot be accessed by itself, but the property will be kept outside to form a closure var name ='deng'; this.say = function () {console.log(name);//function access to the private variables by their method}} var deng = new Deng ( ); duplicated code

4. Module development to prevent pollution of global variables

var name = 'bcd' ; var init = ( function () { var name = 'abc' ; function callName () { console .log(name);} return function () {callName(); })())init(); Copy code

Saving the function inside to the outside will inevitably form a closure.

Execute function immediately

The function used for the initialization function will be destroyed immediately after execution (the function must include AO if the function has the operation immediately executed function)

( Function () {}())( function () ())() Copy code

Why can the immediate execution function be written like this: Use parentheses to turn the function declaration into an expression, and only the expression can use the execution symbol

var A = ( function ( A, B, C ) { return A + B + C;} ( . 1 , 2 , . 3 )) //standard syntax duplicated code

Solve the problem of polluting global variables by executing functions immediately

+ function () {} () -> normal function preceded by a number sign will be able to perform its function becomes immediately duplicated code

prototype

Created as an empty object during function declaration 1. Definition: The prototype is an attribute of the function object, which defines the common ancestor of the object created by the constructor. The object generated by the constructor can inherit the properties and methods of the prototype. Prototypes are also objects.

1.Car.prototype.xx = 'xx'; 2.Car.protetype = {xx: 'xxx'} copy the code
Go { Person :fn{ },Person.prototype={ Person.prototype.name = 'qugao' }} Person.prototype.name = 'qugao' ; function Person ( age ) { //AO{this ={this.age = age;},} this.age = age;} var person = new Person (19); console.log (person.name);//attribute name to access the prototype copy the code

2. The first application of the prototype: extracting common attributes

function Car ( color, owner ) { this .color = color; this .owner = owner;} Car.prototype.height = 14000 ; Car.prototype.lang = 4900 ; Car.prototype.carName = 'BMW' ; var car = new Car( 'red' , 'qugao' ); console .log( 'color:' +car.color, 'holder:' +car.owner, 'car height:' +car.height, 'car length: ' +car.lang, 'Car name:' +car.carName); Copy code

3. View the constructor property of the object and modify the pointer of the constructor through the prototype object

function Car () {} Var CAR = new new Car (); //car.constructor => Car funtion () {} copy the code
function Person () {}Car.prototype = { constructor : Person} function Car () {} Var CAR = new new Car (); Console .log (car.constructor); //Fn the Person () {} copy the code

4. The proto attribute stores the prototype pointed to by the object (the attribute of the constructor this object) (the implicit attribute specified by the system) (the prototype point of the current object can be modified)

Person.prototype = { name : 'qugao' , age : 20 , sex : 'male' } function Person () { //= {the __proto__ the this var: var Person.prototype}} = new new the Person Person (); the console.log (Person .__ proto__);//{name: 'qugao', Age: 20 is} copy the code

Modify the prototype pointing through the __proto__ attribute

Person.prototype.name = 'abc' ; function Person () {} var obj = { name : 'sunny' } var person = new Person(); console .log(person.__proto__); //{name:'abc',constructor: fn}person.__proto__ = obj;console .log (person .__ proto__);//{name: 'sunny'} copy the code

Prototype chain

(Object.prototype is the highest level of all prototypes) 1. The same point: store the prototype through the _proto_ property and access the upper level similar scope chain in turn by itself 2. Differences: need to be achieved through first-level inheritance

Td.prototype.lastName = 'deng' ; function Td () {} var td = new Td(); Father.prototype = td; function Father () {} var father = new Father(); Son.prototype = father; function Son () {} var son = new Son(); Copy code

Additions, deletions, and modifications to the prototype chain

Only I can add, delete, check and modify (constructor) delete Td.prototype.age//Delete the prototype chain son.age//->undefined

this points to

this (function scoped context)

The point of this -> Whoever calls the method this points to

Person.prototype = { name : 'gao' , sayName : function () { console .log( this .name);}} function Person () { The this .name = 'B' ;} var Person = new new the Person (); Console .log (person.sayName); //B the console.log (Person.prototype.sayName);//Gao copy the code

this points to

--- Under non-arrow function

  1. Point to the object calling the function, and point to whom it is close to.//That is who calls the function, and whose this points to obj.xxx (xx is a function) then this points to obj
  2. Under the constructor, this is bound to the new object being created,
  3. DOM event, this points to the element that triggered the event
  4. The prototype's this is the same as the function usage//Who calls the prototype's method to whom this points

Specific analysis 1. In the global environment: In the global environment, this always points to the global object (window), regardless of whether it is in strict mode or not

console.log (this.document == document)//trueconsole.log(this == window);//truethis.a = 37; console.log (window.a);//37 copy the code

Function context call

Direct function call: this inside a normal function is divided into two cases, strict mode and non-strict mode. In non-strict mode, this points to the global object (window) by default

function f1 () {return this; }//GO f1 object call method, point windowf1 () === window;//true copy the code

In strict mode, this is undefined

function f2 () { "use strict "; return this;} f2 () === undefined;//true copy the code

This in the object

  1. The definition position of the function does not affect its this point, this point is only related to the object calling the function//It is also who calls it to point
  2. Multi-level nested objects, the this of the internal method points to the object closest to the called function (window is also an object, and the this of the internal object calling method points to the internal object, not window)
var o = { prop : 37 , f : function () { console .log( this ); return this .prop; }); console .log(of()); //Multi-layered function nesting this points to the nearest object this points to the f object f. No prop is in scope Look up the chain= 37 copy the code
var a = of; //Generate closure this points to windowconsole.log(a());//There is no prop attribute in window= undefined var o = (prop: 36); function independent(){ console.log(this) ; return this.prop;} of = independent ; console.log (of ());//recursive function to point the nearest multilayer object, point up to find no ff = "36 copy the code
= {OB g : Independent, prop : 42 }; Console .log (OBG ()); //nested nearest point, point g target = "42 copy the code

In the non-strict mode of ES5, the this in the general code global and this in the function all point to the window

function a () { console .log( this );} let obj = { c : function () {A ()}} obj.c () //window duplicated code

This in the prototype chain

The this of the method in the prototype chain still points to the object that called it,

var o = { f : function () { console .log( this ); return this .a + this .b; }); var p = Object .create(o); //Object.create(o) means to point to the _proto_ property of p o a prototype implementation of the prototype chain pa = 1; pb = 4; console.log (pf ());//call the case f p parent prototype method but this point is called the method of the object copy the code

This in the constructor

The this in the constructor will be bound to the newly created object. After encountering the new keyword, the constructor will implicitly create an empty object of this, and then write the following this.xx into the empty object, and finally return, If you write your own return, this object will be replaced. Example:

function Person () { The this II.A = 37 [ ;} var F = new new the Person (); Console .log (FA); //37 [ duplicated code
function Person () { This II.A = 37 [ ; return { A : 38 is }; //custom return this object covering an object should be returned} var f = new Person () ; console.log (fa); duplicated code

call&apply

This in call&apply points to the object written by the first parameter

function add ( c, d ) { console .log( this .a + this .b + c + d) //16//34}var o = {a:1, b:3};add.call(o, 5,7);add.apply(o,[10,20]); Copy code

this points to the summary

  1. Function precompilation process: this->window
  2. Global scope: this->window
  3. call/apply can change the point of this when the function is running
  4. obj.function(); func() (this inside points to obj)

call

(Borrow other people's methods to achieve the functions you need) Format: call the first parameter is the object (change this to this = obj), the second is the normal parameter transfer (one-to-one correspondence) Example:

function Person ( name, age ) { this .name = name; //obj.name = zhao; this.age = age;//obj.age = 300; console.log(this);}var person = new Person( 'deng', 100);//this first point Personvar obj = {} Person.call (obj , 'zhao', 300);//this point the second obj duplicated code

apply

Format

xx.apply ( the this , [XX]) //first parameter of the object, the second must be an array [arguments] duplicated code

The function of call and apply is to change the direction of this, the difference is that the parameter list is different

  1. Inheritance: 1. Realize inheritance layer by layer inheritance through prototype chain 2. call, apply method borrows constructor
  2. Shared prototype, multiple constructors share one prototype Disadvantage: changing a prototype attribute will cause all prototype attributes to be modified
Father.prototype.lastName = 'qugao' ; function Father () {} function Son () {} = Son.prototype Father.prototype; var Son = new new Son (); duplicated code

Holy Grail Mode

Realize intermediate inheritance through a new constructor

function inherit ( Target, Origin ) {} function F () {} F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constuctor = Target; Target.prototype.uber = Origin.prototype;}Father.prototype.lastName = 'deng' ; function Father () {} function Son () {} The inherit (Son, Father); var Son = new new Son (); var Father = new new Father (); duplicated code

try catch()

try {} If an error occurs in try, the code in try after the error will not be executed

catch(e){} If there is an error in the try, catch will catch the error and encapsulate the error information in an object (e), if there is no error in the try, the catch will not be executed

//The first statement is executed and the second error occurs.//The subsequent code is not executed. try{console.log("a")}catch(e){console.log(e);}//Can only be followed by catch//after the parentheses after executing the executed immediately try catch finallyfinally {} copy the code

The information corresponding to the six values of error.name (error name): 1. EvalError: the use of eval() is inconsistent with the definition -> eval() is not allowed to use by yourself 2.RangeError: the value is out of range 3.ReferenceError: illegal or unrecognized Reference value 4. SyntaxError: A syntax analysis error occurred 5. TypeError: The operand type was incorrect 6. URLError: The URL processing function was used improperly

Strict mode: es5 "use strict" 1. It is no longer compatible with some irregular syntaxs of es3 (parts that conflict with es3). Use the new es5 specification.
2. Two usages: a. Global strict mode (top) b. Local function strict mode (recommended) 3. It is a line of string, which will not affect browsers that are not compatible with strict mode. 4. Does not support with, arguments.callee, func.caller, variables must be declared before assignment, local this must be assigned (Person.call(null/undefined) assignment is what it is), and it is refused to repeat attributes and parameters


with(){}
Function: Change the scope chain of the current execution, the parameters passed in the brackets will be placed at the top of the scope (beginning of the scope chain) Disadvantages: increase the js kernel consumption, affect the execution speed (modify the scope chain consumption Memory) example: var person = {name: "gao"} function test (){ var name = "qu";with(person){console.log(name)}} test();

Array-like

  1. You can use the attribute name to simulate the characteristics of the array
  2. The length attribute can be dynamically increased
  3. If the push method is forcibly called by the class array, the realization of the extension class array of the attribute will be carried out according to the position of the length attribute value
  • If the attribute is an index (number) attribute, it must have a length attribute
  • Advantages: It is more convenient to store data, combining objects and arrays
  • Disadvantages: not all array methods can be used
var obj = { "0" : "a" , "1" : "b" , name : "gao" , "length" : 2 , "push" : Array .prototype.push, "splice" : Array .prototype. } obj.push splice ( 'C' ); obj.push ( 'D' ); duplicated code

Implementation of push method of class array

The Array .prototype.push = function ( target ) {obj [obj.length] = target; obj.length ++;} copy the code

DOM object

DOM -> Document Object Model

DOM defines the methods needed to represent and modify documents. The DOM object is the host object, which is defined by the browser manufacturer, and is a collection of objects used to manipulate the functions of html and xml. Some people say that DOM is a standard programming interface for html and xml

The DOM object actually refers to the tag object (DOM element) captured by the document

DOM object operation is actually to modify the properties of the object (including inline css)

document represents the entire document

Modify the css of the DOM object

var DOM = Document .getElementsByTagName ( "" ) [ 0 ]; dom.style.color = "Red" ; //change the font color copy the code

Create node

createElement -> process: first create and then put the node into the required container

//The first step is to create a node var div = document.createElement("div");//The second step is to put the node into the required container//The wording in the body document.appendChild(div);//put How to write ordinary nodes var div1 = document.getElementById("div"); ->div1.appendChild(div); Copy code

Basic DOM operation

View element nodes (capture node objects)

//Captured by element id returns a single object and only captures the first one.//Capture name and id are case-insensitive below ie8 compatible document.getElementById("");//Capture class array ie8 by class name and None of the following documents.getElementsByClassName("");//After capturing and selecting by tag name, the returned is a class array document.getElementsByTagName("");//What is captured by tag name property is returned is a class array node list with only part of the tag name Can be effective (label form that can submit data, etc.) document.getElementsByName();//query is used to save a copy, the original disappears and the copy will not disappear//Selecting the matching label will only capture the first element. The following two selectors ie7 and the following version is not document.querySelector ( "div> span a" );//select all labels in line with the returned array is a class document.querySelectorAll ( 'div'); duplicated code

Traverse the node tree

The structure of each html document is a tree, html is the top, which is the document

  1. parentNode -> parent node (the top parentNode is #document)
  2. childNodes -> child nodes (all child nodes)
  3. irstChild -> the first child node
  4. lastChild -> the last child node
  5. nextSibling -> the next sibling node
  6. previousSibling -> the previous sibling node

Traversal based on element node tree

(The element node is the html tag) (the root node of the element node has no document)

a.parentElement -> returns the parent element node of the current element (IE is not compatible) b.children -> only returns the element child nodes of the current element c.childElementCount ===children.length The number of child element nodes of the current element (IE is not compatible) d.firstElementChild -> returns the first element node (IE is not compatible) e.lastElementChild -> returns the last element node (IE is not compatible) f.nextElementSibling/previousElementSibling- >Return to the next/previous sibling element node (IE is not compatible)

html node type

(Value returned by nodeType)

Element node --1 Attribute node --2 Text node --3 Comment node Comment --8 document--8 DocumentFragment --11

Example: div.childNodes

NodeList(9) [text, comment, text, strong, text, span, text, em, text]0: text//Space, comment and text are all text nodes 1: comment//Element node 2: text3: strong4: text5: span6: text7: em8: textlength: 9 replication Code

4.attributes of the node

a.nodeName: the label name of the element, expressed in uppercase, read-only b.nodeValue: the text content of the text node or Comment node, readable and writable c.nodeType: the type of the node, read-only d.attribute: the attribute collection of the Element node

A method of node

Node.hasChildNodes(); Copy code

note

  1. The getElementById method is defined on Document.prototype, so Element cannot be used, it can only be called by documen.
  2. The getElementsByName method is defined on HTMLDocument, which means that only documents in html can be used (document Elements in xml cannot be used)
  3. The getElementsByTagName method can be used, and the * in the brackets is to select all elements
  4. HTMLDocument.prototype defines some commonly used attributes, body and head respectively refer to the tags document.head -> tags in the html document
  5. The documentElement property is defined on Document.prototype, which refers to the root element of the document. In the HTMl document, it always refers to the element. document.documentElement -> element
  6. The getElementClassName, querySelectAll, querySelector, Document.prototype, Element.prototype classes are all defined

Create node

a. Create element nodes

//What tag name is written in the brackets is what tag is created document.createElement(); copy the code

b. Create a text node

//What is written in it is the text document.createTextNode(); copy the code

c. Create a comment node

//What you write is what document.createComment(); copy the code

d. Create a new blank document fragment

document .createDocumentFragment(); Copy code

Node API

Insert node

//(front number is the parent node.) The node is substantial shearing PARENTNODE.appendChild (); (inserting a node before the node b)//PARENTNODE.insertBefore(a, b); duplicated code

Delete node

//delete a node by node father, but not actually delete the cut parent.removeChild ();//delete themselves through their own node, the same shear child.remove (); Copy the code

Replacement node

//Parent call, replace the old element with the new element (also cut) parent.replaceChild(new ,origin); copy the code

DOM object properties

  1. innerHTML property, directly use this property to return the entire node structure of the label, direct assignment will cover the entire structure, you can use += to add content, you can modify the structure of the entire node

    //generating node directly before span node coverage, but also with inline style div.innerHTML = "<span style = ' color: red'> 123 </span>" copy the code
  2. innerText (not compatible with Firefox), returns the text content in the node. Pay attention to the structure of the node when assigning and modifying it. Direct assignment will affect the structure of the node.

    //The span node inside will be overwritten and become a plain text node div.innerText = 123; Copy code
  3. textContent (equal to innerText) " The old version of IE is not good enough to generally use innerText

Element node API

//Set element node attributes, you can add id, class and other attributes ele.setAttribute(attribute name, attribute value);//Get element node attributes ele.getAttribute(attribute name); copy code

Event object

Binding event handler

ele.onxxx(event type) = function () {} Copy code

Binding a processing function to an event of an element a. Compatibility is very good, but only one processing function can be bound to the same event of an element b. Basically equivalent to writing on the HTML line-"Handle binding method

div.onclick = function () {} == < body onclick = "console.log()" > </body > Copy code
obj.addEventListener(type,fn, false ) //type -> event type and string "click" The first parameter//fn -> the second parameter of the processing function//false -> Bubbling or directly capturing the first parameter three parameters//IE9 is not compatible with the following, you can bind an event handler for multiple copy the code

IE unique method

obj.attachEvent( "on" +type,fn); Copy code

Note: One event can be bound to multiple handlers

The operating environment of the event handler (this points to)

//The program this points to the dom element itself ele.onxxx = function(event){)//The program this points to the dom element itself obj.addEventListerner(type,fn,false)//The program this points to windowobj.attachEvent('on' +type,fn) Copy code

Compatible methods for encapsulating and adding events

function addEvent ( elem, type, handle ) { if (elem.addEventListener){ elem.addEventListener(type, handle, false )} else if (elem.attachEvent){ elem.attachEvent( 'on' +type, function () {Handle.call (elem)})} the else {elem [ 'ON' + type] = handle;}} copy the code

Dismiss event handler

Note: If an anonymous function is bound, it cannot be released)

ele.onclick = false | '' | null //It is better not to use anonymous functions for fn in this, otherwise it is not easy to remove ele.removeEventListerner(type, fn, false);//ele.datechEvent('on'+ type, fn) Copy code

example:

div.onclick = function () { console .log( 'a' ); this .onclick = null ; //Unbind event}div.addEventListener("click",test,false);div.removeEventListener('click',test,false); function test(){ console.log("a");} Copy code

Event handling model

Execution order

The execution order of event bubbling and capture is capture first and then bubbling + bind first and execute first

Event bubbling

(Non-visually) nested elements will have the function of event bubbling, that is, the same event will bubble from the child element to the parent element. (Bottom-up) (Bubbling in code structure) Why bubbling: Child elements inherit the binding events of the parent element

Event capture

(Non-visually) nested elements have the function of event capture, that is, the same event is captured from the parent element to the child element (event source element) (top to bottom). (Contrary to the bubbling event transmission direction, first outside and then inside)

(***IE did not capture the event)

Events such as focus, blur, change, submit, reset, select, etc. do not bubble

Cancel bubbling and organize default events

1. Cancel bubbling a.W3C standard that event.stopPropagation (); IE9 or lower but not exclusive b.IE event.cancelBubble = true; c package cancel function stopBubble (event) bubbling.;

2. prevent the default event:

Default event-form submission, a tag jump, right-click menu, etc.

//It is only useful when the event is bound by the handle (that is, written in the line) return false; the event registered by the object property is valid//W3C annotation, IE9 and below are compatible with event.preventDefault();//Compatible with IEevent.returnValue = false; copy the code

special case:

<a href = "javascript:void(false)" ></a> Copy code

You can also cancel the default event: write code later and execute the js code when you click the a tag

Event object

When each event is executed, the system will encapsulate all event attributes in an object, which can be accepted in the formal parameter definition of the processing function

Event object property analysis

  1. targe: event source object Usage e.target returns the element node of the triggered event
  2. clientX/clientY returns the x/y coordinates of the mouse in the client area of the window.
  3. screenX/screenY returns the x/y coordinates of the mouse relative to the user's screen
  4. x/y Get the x/y pixel coordinates of the mouse pointer position relative to the parent document.
    1. In IE. Versions below IE8 are not relative documents. Their values are the same as the values of clientX and clientY, relative to the window client area
  5. layerX/layerY returns the x/y coordinates of the mouse position relative to the object that triggered the event
  6. pageX/pageY Get the x/y pixel coordinates of the mouse pointer position relative to the parent document
  7. preventDefault() prevents the execution of the default action

Compatible attribute judgment

var event = e || window .event (unique in IE); copy the code

Event source object

var target = event.target || event.srcElement; Copy code

Example written by bubbling mechanism and event source object

var ul = document .getElementsByTagName( "ul" )[ 0 ];ul.onclick = function ( e ) { var event = e || window .event; var target = event.target (only this for Firefox) || event.srcElement (IE only has this); console .log(event.target.innerText);} //First by adding events to the parent element, then all child elements through the bubbling mechanism will get the event of the parent element, and finally through the event li source acquired attribute copy the code

Mouse and keyboard event classification

Mouse event

click, mousedown (mouse down), mousemove (mouse movement), mouseup (mouse release), contextmenu (right mouse click to display the menu), mouseover (mouse passing), mouseout (mouse completely leaving), mouseenter (entering or passing through) ),Mouseleave (mouse pointer left) copy the code

  1. Mouseover and mouseout can be triggered on both the parent element and its child elements. When the mouse passes through an element, the number of triggers depends on the number of child elements.
  2. Mouseenter and mouseleave are only triggered on the parent element, and only once when the mouse passes through an element.
  3. mouseover and mouseout are triggered before mouseenter and mouseleave

Distinguish whether the mouse is a left-click or a right-click. Only the button attribute in the onmousedown and onmouseup event objects can be judged. 0 is the left button and 2 is the right button. DOM3 stipulates that click can only monitor the left button.

Keyboard events

1. There are only three events

onkeydown, onkeypress, onkeyup //trigger sequence onkeydown> onkeypress> onkeyup//When press down a button to trigger the event keydown keypress and then finally release the trigger keyup copy the code

2. Difference

//You can listen to all the keyboard keys onkeydown//character classes can only monitor key (ASCII codes) can be returned by the ASCII key charCode last property//to convert to a character by string.fromcharcode onkeypress copy the code

Keyboard event object properties

1.key returns the name of the key and is also case sensitive

Text operation event

oninput content changes//Inside the event is triggered onchange//modify the content loses focus after the trigger event onfocus/onblur//get/lost focus event trigger copy the code

System trigger event

1.sroll

Date object

//Date () constructor var date the date provided by the system = new Date (); duplicated code

API of date object

//Date(); Returns the detailed time information of the current time var date = new Date();//Returns the current time and encapsulates the information in a new object//Returns the date in the date object is the day of the week 0 -6 Sunday is 0 var day = date.getDay(); var date1 = date.getDate();//The date in the returned date object is the day of the month 1 -31 var month = date.getMonth()+1;//Return the month from the date object 0-11 var year = date.getFullYear();//Return the year- Do not use getYearvar hours = date.getHours();//Return the hours of the current time var minutes = date.getMinutes ();//Returns the current time in minutes var seconds = date.getSeconds();//Returns the current time in seconds var milliSeconds = date.getMilliseconds();//Returns the current time in milliseconds var times = date. getTime ();//returns the number of milliseconds since January 1, 1970 (epoch time) since copy the code

Timer

setInterval()

How many seconds to execute an unlimited number of executions (returns the unique identifier of this timer)

serTimeout is executed once every few seconds (returns the unique identifier of this timer)

//Infinite execution function setInterval(fn(){},time(milliseconds))serTimeout(); ->How many seconds are executed once but only once//The previous string is executed as js code setInterval("string", 100)-" Copy code

clearInterval,clearTimeout clear the corresponding timer

clearInterval (infinite timer identification) //-------clearTimeout (limited timer identification); copy code

The timer methods are all defined on the window, so this points to the window

arguments

The argument list is used to receive the object formed by the argument passed by the calling method

//is equal to the first parameter arguments [0] to copy the code

If the value of argumens is modified, the value received by the formal parameter will also be modified

function Test ( name, Age ) { arguments [ 0 ] = 'HH' ; the this .name = name; Console .log ( the this .name)} Test ( 'qugao' , 12 is ); duplicated code

argumenrts.callee

Pointing to self reference is often used to execute functions immediately

function test () { console .log( arguments .callee); //arguments.callee == test} test(); var foo = (function (n){ if(n == 1) return 1; return n * arguments.callee( n - 1);//this case their arguments equal to the function performed immediately}) (100) copying the code

caller

It is the attribute of the method that returns the environment in which it is called (executes its own method)

function aa () {dd();} function dd () { Console .log (dd.caller);} AA (); duplicated code

JSON object

JSON is a transmission data format (using objects as a template, it is essentially an object, but the purpose is different, the object is for local use, and json is used for transmission) In order to distinguish between json and ordinary objects, all attribute names are specified Double quotes

JSON = { "key" : "value" }; Copy code

Two methods: JSON is a static class, similar to Math, which encapsulates the json method

The JSON .parse (); //String -> json string to json format JSON.stringify ();//json -> string json format into a string copy the code

Rendering engine mechanism

1. Scan the html code first to generate the htmlDOM tree (file download is completed at the end of parsing) First depth first, then breadth first

//Simulate the DOM tree html 1 head 2 body5title 3 meta4 div6 ..... Copy code

2. After the DOMtree is parsed, the cssTree is parsed. 3. After the cssTree is parsed, the rendering engine will put together cssTree and domTree to form a randerTree. At this time, the rendering engine will actually start page drawing (one pixel per pixel Draw from top to bottom)

4. Page rearrangement (refactoring) (affecting page efficiency) reflow (should be avoided) (operations that affect the layout will cause page rearrangement)

  • Add and delete DOM nodes, change the width and height of DOM nodes, and change position
  • dispaly none -> block
  • offsetWidth offsetLeft (randerTree will be reconstructed)

5.repaint repaint (relatively small impact) only modify a part (change the background image, font color, etc. do not affect the page layout)

Load JS files asynchronously

Does not block the loading of js documents and opens up a timeline

Disadvantages of JS loading: The loading tool method does not need to block the document. Excessive js loading will affect the page efficiency. Once the network is not good, the entire website will wait for js to load without subsequent rendering.

3.schemes of asynchronous loading

  1. defer (only available for IE) Asynchronous loading is written in the tag of the tool method, but it will not be called until the DOM document is completely parsed. You can write code in the tag

    Example: <script src ='xxx.js' defer></script> Copy code
  2. async? Asynchronous loading, executed after loading, async can only load external scripts, and cannot write js in the script tag

  3. Asynchronous by creating DOM and inserting it

    var script = document .createElement( 'script' ); script.type = "text/javascript" ; script.src = 'xxx.js' ; script.onload = function () {test();} document .body.appendChild(script); Copy code

JS loading timeline

  1. Create a Document object and start parsing web pages. After parsing HTML elements and their text content, add ELement objects and Text nodes. At this stage, document.readyState ='loading'
  2. When encountering css outside the link, create a thread to load, and continue to parse the document.
  3. When encountering script external js, and without setting async or defer, the browser loads and blocks, waits for js to load and executes the script, and then continues to parse the document.
  4. When encountering script external js, and setting defer, async, the browser creates a thread to load, and continues to parse the document. For async attribute scripts, the script will be executed immediately after loading. (Asynchronous use of document.write() is prohibited)
  5. When encountering img, etc., the dom structure is now parsed normally, and then the browser loads the src asynchronously, and continues to parse the document
  6. When the document is parsed, document.readyState ='interactive'
  7. After the document connection is completed, all the scripts for setting defer will be executed in order. (Note the difference in async, but the use of document.write() is also prohibited)
  8. The document object triggers the DOMContentLoaded event, which also marks the transition from the synchronous script execution stage to event-driven
  9. When all async scripts are loaded and executed, img, etc. are loaded, document.readyState ='complete', and the window object triggers the load event
  10. Since then, processing user input, network events, etc. in an asynchronous response

Streamline -> Document parsing refers to the DOM tree structure

  1. Create a Document object and start parsing the page. Now the readyState is'loading'
  2. Continue to parse,
  3. Encountered link creates an asynchronous thread to load the src file,
  4. When the external js is not set to be asynchronous, it will block and wait for the file to download, and if it is set to be asynchronous, it will create an asynchronous thread to load the external file.
  5. When encountering img, the dom structure is parsed first, and then the browser will load the src asynchronously.
  6. When the document is parsed, readyState ='interactive', the scripts that set the defer will be executed sequentially to complete the document loading and enter the event-driven (click) interactive monitoring event.
  7. When all asynchronous threads (src async) are executed, eadyState ='complete', and the window object triggers the load event. From then on, user input, network events, etc. are processed in an asynchronous response mode

Mainly in three steps

  1. Create a Document object and start parsing the document readyState ='loading'
  2. Document parsing completed readyState ='interactive'
  3. The document is parsed, loaded, and executed readyState ='complete'

Verify the document loading process

//1. Print readyState directly in the document console.log(document.readyState);--->loading//2. Use window.onload event window.onload = fn(){console.log(document.readyState); } -> complete//3 using the document loading event listener xx.onreadystatechange = fn () {document.readyState) ;.} - "interactive copy the code

Browser parsing dom process

What is dom

When we browse a page, the browser obtains the content of the page through a network thread. At this time, only the byte stream of the html file is obtained. The byte stream of the html file cannot be understood by the rendering engine, so we must first convert it to rendering The structure that the engine can understand, this structure is dom, which is often referred to as the dom tree, and the form of expression is the html tags that we can see with the naked eye.

How the dom tree is generated inside the rendering engine, there is a module called the html parser (HTMLParser), which is responsible for converting the html byte stream into the dom structure. Refer to the figure above, the analysis process is divided into 2 steps:

  1. Convert byte stream to token through tokenizer;
  2. The token is parsed into a dom node, and the dom node is added to the dom tree.

In this process, one thing you should notice is that the html parser does not wait for the entire document to be loaded before parsing, but the html parser parses how much data is loaded by the network process .

dom meets js

is parsing to

<script>
Before labeling, the parsing process is still the same as described above. But parsed to
<script>
When tagging, the rendering engine judges that this is a script. At this time, the html parser will pause the parsing of the dom, because the next js may need to modify the currently generated dom structure.

If

<script>
The external js resource is introduced in the tag. After the js file is downloaded, the html parsing work will continue. If the network is slow, the user will obviously feel the page freezes and is not smooth. Therefore, js will block the parsing of html .

Defects of js directly operating dom

When we call

document.body.appendChild(element)
To add an element to the body node, the rendering engine first adds the element node to the body node, and then triggers tasks such as style calculation, layout, drawing, rasterization, and synthesis. We call this process rearrangement. In addition to rearrangement, it may also cause redrawing or compositing operations, which can be described as affecting the whole body. If you modify the dom directly every time you modify the interface, although for simple applications, you will not feel any problems, but for complex applications, the page structure is more complicated, not only the code is not easy to maintain, but also the performance is greatly affected .

Regular expression

Regular expression RegExp

1. Create

a. Literal creation

var REG = /ABC/ ; (recommended) copying the code

b. Constructor creation

//(without new references to the same address, configured like object) var reg = new RegExp ( 'string') copying the code

2. Attributes

I //g//ignoring capitalization performing a global matching (matched to the last character) m//match a plurality of rows with a string/n m on the need to match another row var reg =/abc/igm; duplicated code

3. Expression

[] A representation can only be written in one digit (you can use interval representation)

//az AZ may var reg =/[az AZ]/igm;//[Az] in ASCII table order var reg =/[Az]/igm; duplicated code

Write it in the interval, except for this.

//Called or, in line with either of these two (abc|bcd)//These two arbitrary combinations plus a number (abc|bcd)[0-9] var reg =/(abc|bcd)[0-9]/igm; Copy code

4. Metacharacters

\w //The interval represented is [0-9A-z _]\W//and/w reversed\d//0-9\D//\d reversed\s//blank character\t tabulation (Table)/nnewline\rcarriage return\vvertical tab\f formfeed\S//and/s reverse\b//match the word boundary "abc abc" ac is the word boundary\B and///b inverted "abc abc" bunicode encoding///u0000 duplicated code

5. Quantifiers

How long can greedy matching selection be added after the quantifier? Cancel greedy matching

a. + a+ //Represents a can appear once or several times b.? a?//It means that a can appear 1 time or 0 times c. * a*//It means that a can appear 0 times or several times and it will return d. {} a{2,3}//There is the number of matches, According to several combinations, press more to take e. $//end with what to copy the code

6. Regular expression method

1. The exec method, retrieve the value specified in the string. Return the found value and determine its location.

//Returns an array type, with a successful match character index, the original array reg.exec (str) copying the code

a. According to the expression matching, it will return if it meets the rules, the return is a class array, if it does not meet the requirements, it will return null b. Execute once exec to move the subscript of str backward. The second execution is really the first The record index after one execution and return starts. c. When the match has not yet started, the lastIndex is 0. Once the match is successful, the value of lastIndex will become the index of the string matching successfully.

var str = 'aa baa babab' ; var reg = /[\w]{3}/g ; //match three consecutive characters console.log(str); console.log(reg.lastIndex);//0console.log (reg.exec (str));//baaconsole.log(reg.lastIndex);//6console.log(reg.exec(str));//bab copy the code

2. The test method, retrieve the value specified in the string. Returns true or false.

reg.test (str); -> returns to true to false //use regular expression rules to verify compliance with the string var str = '123abc123'; var reg =/^ [/d] +/; duplicated code

7. Methods of String object supporting regular expressions

The search() method is used to retrieve a specified substring in a string, or retrieve a substring that matches a regular expression.

var STR = '123abcabc' ; var REG = //+ D/G ; //return the first matching is successful subscript str.search (regular | string) copying the code

The match() method can retrieve a specified value within a string, or find a match of one or more regular expressions.

var STR = 'abc11' ; var REG = //D/G ; //Returns an array of classes, which is stored in line with the rules of string str.match (regular | string) copying the code

The replace() method is used to replace some characters with other characters in a string or replace a substring that matches a regular expression.

  • Parameter 1: Required.

    • The RegExp object that specifies the substring or pattern to be replaced. If it is a string, use it as the direct text mode to be retrieved, instead of first being converted to a RegExp object
  • Parameter 2: Required. A string value. Specifies the replacement text or the function to generate the replacement text.

  • Return value: a new string, generated by rules

    var str = 'aavv' ; //(\w)\1 means two numbers one by one\1 means the first matching var reg =/(\w)\1(\w)\2/g;//At this time, if the first parameter is a string, it will only match once console.log(str.replace('a','c'))////$1 indicates the first matching paragraph in accordance with the regularity console.log (str.replace (reg, '$ 2 $ 2 $ 1 $ 1')) console.log (str.replace (reg, function ($, $ 1, $ 2) {return $ 2 + $ 2 + $ 1 + $ 1;})) copy the code

The split() method is used to split a string into an array of strings

var str = 'aabb' ; var demo = str.split( '' ); //Return value: an array//str.split(separator (string or regular), howmany (limit the maximum optional return string Length)) copy code

Strict mode

The "use strict" directive is only allowed to appear at the beginning of a script or function.

Why use strict mode: 1. Eliminate some unreasonable and imprecise aspects of Javascript syntax and reduce some weird behaviors; 2. Eliminate some unsafe aspects of code running and ensure the safety of code running; 3. Improve the efficiency of the compiler and increase the running speed; Pave the way for the new version of Javascript in the future. "Strict mode" embodies the development direction of Javascript that is more reasonable, safer and more rigorous. Mainstream browsers, including IE 10, have already supported it, and many major projects have begun to embrace it in an all-round way.

Strict mode restrictions

1. It is not allowed to use undeclared variables (including objects, etc.) 2. It is not allowed to delete variables or objects. 3. The same variable name is not allowed. 4. Octal is not allowed. 5. Escape characters are not allowed. 6. It is not allowed to assign values to read-only attributes. 7. It is not allowed to assign a value to a property read using the getter method. 8. It is not allowed to delete an attribute that is not allowed to be deleted. 9. The variable name cannot use the "eval" character string. 10. The variable name cannot use the "arguments" string. 11. The following statements are not allowed. 12. For some security reasons, variables created in the scope of eval() cannot be called. 13. Prohibit this keyword to point to the global object.

Reserved keywords

implements interface let package private protected public static yield

Vue two-way binding implementation

We can directly define a new property on an object or modify an existing property through the Object.defineProperty method. Eventually this method will return the object.

Syntax: Object .defineProperty (Object, propertyName, descriptor) Examples: Object .defineProperty (Object, 'name' , {....}) copy the code

parameter

object required. The object on which to add or modify attributes. This may be a native JavaScript object (ie, a user-defined object or a built-in object) or a DOM object. propertyname is required. A string containing the name of the attribute. Descriptor required. Property descriptor. It can target data attributes or accessor attributes.

Descriptor content: [value] The value of the attribute, the default is undefined. [Writable] Whether the attribute is writable, if it is set to false, any operation to rewrite the attribute will be invalid (but no error will be reported). For attributes directly defined on the object as in the previous example, this attribute is the default value of this attribute Is true. [Configurable]] If it is false, any attempt to delete the target attribute or modify the following attributes (writable, configurable, enumerable) will be invalidated. For attributes directly defined on the object as in the previous example, this attribute has this attribute The default value is true. [Enumerable] Whether it can be traversed in a for-in loop or listed in Object.keys. For the attributes defined directly on the object as in the previous example, the default value of this attribute is true. [Get] Once the target object accesses the property, it will call this method and return the result. The default is undefined [set] Once the target object sets this property, this method will be called. The default is undefined.

let temp = nullObject.defineProperty({}, 'name' ,{. get () {Retrun TEMP;} SET ( Val ) {}} TEMP = Val) copy the code

summary

It can be seen that we can define and control some special properties by using Object.defineProperty, such as whether the property is readable, whether the property is enumerable, and even modify the setter and getter of the property

The principle of two-way binding

Use this attribute to add a property name to the object, calling the property name to add and delete will trigger the set.get method inside to achieve data binding

js advanced

Function stabilization

The concept : anti-shake function (debounce), refers to the trigger event, the function can only be performed once in n seconds, if the trigger event within n seconds and triggered the event, it will recalculate the execution time delay function.

The key "anti-shake function," is that in an event occurred some time later, before the implementation of a specific action . Triggering an event during this timing time will cause the timing time to be reset, and the time will be waited again

solution

The main point of function anti-shake is that a setTimeout is needed to assist in the implementation, and the code that needs to be executed is delayed. If the method is triggered multiple times, clear the delayed execution code recorded last time with clearTimeout , and restart the timing. If the event is not re-triggered during the timing, the target code will be executed after the delay time has expired.

Implementation

function debounce ( fn,wait ) { var timer = null ; return function () { if (timer){ clearTimeout (timer);} timer = setTimeout (fn,wait); }} function handle () { Console .log ( the Math .random ());} window .addEventListener ( "a resize" , Debounce (handle, 1000 )); duplicated code

General usage scenarios

  1. Search input in the search box. The user only needs to input the last time before sending the request;
  2. User name, mobile phone number, and email input verification;
  3. After the browser window size is changed, the code in the resize event only needs to be executed after the window is adjusted to prevent repeated rendering

Immediate execution version

The so-called version is immediately executed after the trigger event function will not be executed immediately, but carried out after n seconds, if n seconds and triggered the event, it will recalculate the function execution time.

/** * @desc function shake --- "immediate execution version" and "non-immediate release executed" versions of the combination of * @param FUNC function to be executed * @param the wait delay execution time (ms) * @param immediate - --true means immediate execution, false means non-immediate execution **/ function abounce ( fnc, wait, immediate = false ) { let timer = null ; return function () { let content = this ; let args = arguments ; //If it is the second time within the specified time, continue to clear the following delay operation to enter the cooling if (timer) {clearTimeout(timer);}//If it is the immediate execution version if ( immediate) {//If the timer is undefined to be triggered let callNow = !timer;//The specified time after the trigger will become empty. This time will not trigger timer = setTimeout(() => {timer = null; }, wait ); callNow && fnc.apply(content, args);//If the version is not executed immediately, follow the original one} else {timer = setTimeout(() => {fnc.apply(content, args); }, wait) ;} };} Copy code

Function throttling

Concept : **The so-called throttling means that the event is triggered continuously but the function is executed only once in n seconds. **Throttling will dilute the frequency of execution of the function

Timestamp version

function throttle ( fnc, wait ) { let pre = 0 ; return function () { let now = Date .now(); let content = this ; let args = arguments ; //The current trigger event minus the previous trigger time 1 second will trigger if (now-pre >= wait) {fnc.apply (content, args); pre = now;}};} copy the code

Timer version

//Timer version function throttle(fnc, wait) {let timmer = null; return function () {let content = this; let args = arguments;//Used to lock the currently executing timer if there is already a timer in If the timer is executed repeatedly, it will not be executed. If (!timmer) {timmer = setTimeout(() => {timmer = null; fnc.apply(fnc, args); }, wait);} }; } Copy code

Higher order function

  1. A function that receives a function or multiple functions as parameters, such as the built-in js
    map some every filter reduc
  2. Function execution returns a function, such as
    bind
//map receives each item in a function array and executes this method//returns a new array element of the array, the value processed by each item of the original array after receiving the function const arr = [1,5,6,44 ,99,36,77];const res = arr.map(item => item + 1);//The new array returned after calling the function for each item in the original array console.log(res)//[2, 6 , 7, 45, 100, 37, 78] copy the code
Array .prototype.myMap = function ( fn ) { const len = this .length; const newArr = []; for ( let i = 0 ;i <len;i++){ //Each item of the original array is processed by the fn function Push the last value into the new array newArr.push(fn(this[i]))} return newArr}const res = arr.myMap(item => item + 1)console.log(res);//[2, 6, 7, 45, 100, 37, 78] copy the code

Currying function

const res = add( 1 , 2 )( 3 ); console .log(res) //6//Analysis: add function passes in parameters and executes, returns a function, passes in parameters, executes again, and sums const curring = () => {//Create a params set in the closure to pre-store the actual parameters received for each add execution let parmas = []; const add = (...args) => {parmas = parmas.concat( args)//The add function is returned here because we are not sure how many times the add function will be called after execution, and each time it is executed, it returns an add function for its next execution return add}//convert an object into a string or numeric priority [Symbol.toPrimitive]> valueOf >toString> Number//Realize the sum operation based on the process of reconstruction and conversion into a string add[Symbol.toPrimitive] = () => {//Sum the pre-stored params return parmas .reduce ((result, item) = > result + item)} return add} copy the code

Function Currying: Using the function of closure preservation, some information is stored in advance, [preprocessing], for use in the middle and later stages of its lower context.

componse function

Function composition connects the processed functions like a pipeline, and then the data passes through the pipeline to get the final result (chain operation)

const compose = function compose ( ...fns ) { //x is the initial value of the parameters of the small function after compose is executed for the first time return function operate(x){//loop compose argument function list//result is the last function execution The returned result//item is the function currently looped to//reduce iterates from left to right reduceRight from right to left return fns.reduceRight((result,item)=>{//returns the result of the current function execution to result return item (result)}, x) }} const res = compose (fn3, fn1, fn2) (1); duplicated code

Why is js single threaded

  • As a browser scripting language, the main purpose of JavaScript is to interact with users and manipulate the DOM. This determines that it can only be single-threaded, otherwise it will bring very complicated synchronization problems
  • Assuming that JavaScript has two threads at the same time, one thread adds content to a certain DOM node, and the other thread deletes this node. At this time, which thread should the browser use?
  • So, in order to avoid complexity, JavaScript has been single-threaded since its birth

Task queue

concept

  • Single thread means that all tasks need to be queued, and the previous task ends before the next task is executed. If the previous task takes a long time, the next task has to wait forever
  • All tasks can be divided into two types, one is synchronous tasks (synchronous), and the other is asynchronous tasks (asynchronous)
  • Synchronous tasks refer to tasks queued for execution on the main thread, and only the previous task can be executed before the next task can be executed
  • Asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue". Only when the "task queue" informs the main thread that an asynchronous task can be executed, the task will enter the main thread for execution.

Asynchronous task

It is divided into microtasks and macrotasks to distinguish the priority. The priority of microtasks is higher than that of macrotasks.

The promise's then belongs to the micro task

setTimeout

  • Is a macro task
  • It adds an event to the end of the "task queue", so it will not be executed until the synchronization task and the existing events of the "task queue" are processed.

Summary Event loop

Consider children first (micro tasks) and then adults (macro tasks)

  1. The execution stack first executes the synchronous code, encounters the asynchronous code, and throws it into the asynchronous queue until the synchronous queue is executed (js code block, new Promise constructor pre-content)

    console .log( 111 ) new Promise ( ( res,rej )=> { console .log( 222 ) }) //These two items are synchronous code
  2. At this time, the asynchronous queue is executed, and the asynchronous queue has the difference between micro tasks and macro tasks.

  3. The micro task is executed first, and then the macro task is executed. At this time, after the execution of the macro task is completed, the calculation result is fed back to the synchronization task

  4. After the execution of the macro task is completed, start the next round of calculation

  5. It should be noted that all execution processes are executed in the js execution stack, but each time the object being executed changes

    setTimeout ( () => { console .log( 0 );}, 0 ) new Promise ( ( resolve, reject ) => { console .log( 1 ); resolve()}).then( () => { console .log( 2 ); new Promise ( ( resolve, reject ) => { console .log( 3 ); resolve() }).then( () => { console .log( 4 ); }).then(() => { console .log( 5 ); }).then( () => { console .log( 6 ); })}).then( () => { console .log( 7 );}) new Promise ( ( resolve, reject ) => { console .log( 8 ); resolve())).then( () => { console .log( 9 );}) //1 8 2 3 9 4 7 5 60//All microtasks are executed before the macro task is executed, even if it is a continuous copy of the code

Timer task scheduling

  • The timer has an independent module for calculation, such as the timer set at 2 milliseconds, and the timer module will throw into the macro task after 2 milliseconds
  • So it is not executed after the time is up, but enters the execution queue after the time is up.
  • Still have to wait for the execution of the micro task to complete before it will be executed
  • If there are multiple timer tasks, the timer modules will be arranged, and the time end will be put into the macro task queue first
setTimeout ( () => { console .log( '2000' );}, 2000 ); setTimeout ( () => { console .log( '1000' );}, 1000 ); Promise .resolve().then( res => { console .log( "promise" );}) console .log( 2 ); for ( let index = 0 ; index < 3000 ; index++) { console .log( '' );}//2 3000 promise 1000 2000 null character copy the code

The main process and the task queue share memory

let i = 0 ; setTimeout ( () => { console .log(++i);}, 1000 ); setTimeout ( () => { console .log(++i);}, 1000 ); //Two The second settimeout will not be executed at the same time, but it is also written in the first order. The i of the operation is the same i, and if the previous is changed, the latter will get the latest value. Copy the code