A blog post: js introduction knowledge, worth collecting!

Posted by isaacsf on Tue, 08 Feb 2022 15:41:58 +0100


1. Background introduction

In order to improve the network speed, it was solved by Brandon Archie of Netscape, who designed js in 10 working days

1. js standard

ECMAScript is a standard, while JavaScript is the language

2. Basic concepts of js

1. What is js

An object-oriented, cross platform, scripting language that relies on html can be implemented.

2. Application scenario:

  1. Form verification: standardize user input data and interact with background data 2 Web effects: add behavior to the page content and make the page move 3 Game development: aircraft war, playing bricks
    js composition diagram
  2. Internet of things: https://zhuanlan.zhihu.com/p/45509947
  3. h5, the next version of html, is very powerful. At present, we know that h5 is just some tags, which can not perfectly show its strength. After adding js, we can activate the deep-seated functions of these tags.

3. js composition

ECMAScript: Core

BOM: document object model, which provides methods and interfaces for accessing and operating web pages

DOM: browser object model, which provides methods and interfaces for interacting with browsers

3. Basic use of js

1. js write location

1. Tags: script


//Writing position of js code (recommended)
</script><-This is a label indicating the end. You can't Scribble, except for the translation character->
<p>This page requires browser support (enabled) JavaScript. </p>
  • The traditional standard is written in the head
  • In fact, style and script can be written anywhere
  • Modern web is put in the body
  • But. Require appeared After JS, most of them are written in the head to realize asynchronous loading and dependency processing
  • 6 attributes: ⭐
    • async: (optional) indicates that the script will be downloaded immediately without affecting other operations (asynchronous operation) (fill in Boolean)
    • Charset (optional) represents the character set of the code specified by the src attribute. Most browsers ignore
    • defer: (optional) indicates that the execution is delayed until all documents are parsed and displayed (attribute = = attribute value)
    • The address of the js file introduced by the SRC (optional) table
    • type: (optional) you can see that it is the language attribute, that is, the script language attribute.

Asynchronous scripts must be executed before the load event of the page, but they may be executed before and after the event is triggered

Realize XHTML recognition


2. Import js file

The software uses external files, which is convenient for maintenance, fast cache loading and future trend

<script src="main.js"></script>

3. Notes

	js Multiline comment for

2. Strict mode

Add "user strict" at the top of js code

Or add at the top of the function

function (){
    "user strict";
    //Function body

In strict mode, some uncertainties in ECMAScript3 will be handled and errors will be thrown for some unsafe operations

Anonymous production variables are not allowed. Functions do not point to this. Variables or objects are not allowed to be deleted. Functions are not allowed to be deleted. Formal parameters cannot be renamed

3. js output

  1. Document object maturation

    document.write("hollo world");
    //Output label element class content
    document.write("<b>Text bold</b>");
    document.write("Text tilt");
  2. Display in pop-up window

    alert("hollo world");
  3. Pop up the judgment box

    confirm("are you sure");
  4. Pop up input box display

    prompt("hollo world");
  5. Debug window output

    console.log("hollo world");

4. Definition of variables

ECMAScript variables are loosely typed

1. var defined variable

var x;//The var keyword is followed by an indicator or variable name.
/*Rules of indicator: composed of letters, numbers and underscores,
    Can't start with a number --- hump nomenclature
    Cannot conflict with keywords and reserved words

var a=12;//assignment

 var a,b;//Define multiple variable declarations at once
 var c=1,b=2;

 e= 13;//Implicit declaration

2. let definition

let a=12;//Can only be used within the scope domain

3. Constant definition

const a=1;

5. Type of variable

  1. Number type: var num=1;

  2. String type: var str="hollo world";

  3. Boolean type: var t="true",f="false";

  4. Undefined type: var under="undefined";

  5. Empty object type: null;

  6. Object type:

  7. Special form: function, this special type

    var arr=[1,2,3];
    var age=12;
    var obj={

    It should be noted that both arrays and objects are object types

    The first five are simple types or basic types, and the latter are complex types, also known as reference types.

    Myth: null==undefined returns true, but the two are completely different.

  8. View data type: console Log (typeof indicator) typeof is an operator, not a function

1. Boolean type

Operator: Boolean

data typeConvert to true valueConvert to false value
SreingAny string”"(empty string)
NumberAny non-zero value0 and NaN
ObjectAny objectnull

2. Number type

1. Base system
var a = 0b10;//Binary 
var a = 010;//octal number system
var b = 0xA;//Hexadecimal
var c = 0xb;//Lowercase or uppercase letters are acceptable, and hexadecimal is also acceptable
    console.log(a); //8
    console.log(b); //10
    console.log(c); //b

2. Scientific counting method
var num = 5e+5;  //5 times 10 to the 5th power (larger)
var num = 3e-3;//3 times 10 to the - 3rd power (decimal)

3. Floating point precision loss

This is a common problem of floating-point calculation based on IEEE754 values

var a=0.1+0.2;console.log(a);//The result is 0.300000000000000 4
var b=(0.1*10+0.2*10)/10;console.log(b);//Resolution of precision loss

4. Scope

[5e-324, 1.797e+0] exceeding is - Infinity (negative infinity) and infinity (positive infinity)

Infinity cannot be calculated



var a = 1;
var b = 'two';
var c = a - b;
console.log(c); // NaN is not a number
console.log(typeof c); // NaN: not a number is not a number

In js, NaN is used to represent a non numeric special value. When it is found that the operation cannot be performed, js will not report an error, but will return a NaN

Precautions for NaN:

  • The type of NaN is number, which represents a non number
  • NaN is not equal to any value, including NaN itself
  • You can judge whether it is a number through isNaN(). When false is returned, it means it is a number
6. Application of NaN
var a = 123; 
var b = "abc"; 
console.log(isNaN(a)); // false 
console.log(isNaN(b)); // true 
console.log(isNaN(c)); // true 

The isNaN() function is used to detect whether the data is of non numeric type

7. Conversion

Operator: Number

3. Character type

1. Escape character
Single quotation marks can't wrap single quotation marks, but can only wrap double quotation marks, that is, you can't wrap yourself.
 It's really not possible to use backslash \ escape character (\)

\nLine feed
''Single quotation mark
'Double quotation mark
2. Character splicing
var lang="Java";lang+="Script";console.log(lang);
var lang="num";lang+=1;console.log(lang);


All types except null and undefined can be converted to strings using toString

But the object is converted to string and output as [object Object]

var str=true.toString();

Special application

Convert decimal to other decimal, and the output result is a string

let num=10;


The concept is the same as toString(), but the usage is different

var str=String(true);

5. Template string
let a=97;
let str=`a=${a}`;
//Not only that, you can also output spaces
console.log(`a       b`);//a      b

4. object type ⭐⭐

1. Concept ⭐⭐⭐

The object in ECMAScript is actually a collection of data and functions. All new variable types are objects.

2. Object creation
let obj=new Object();//Omitting parentheses is not recommended
let arr=new Array();//Create an array object

3. Properties and methods ⭐

Each object type of data has the following properties and methods (except DOM & BOM of the host object)

  1. Constructor: retains the function used to create the current object, that is, the constructor is Object();

  2. hasOwnProperty(propertyName): used to detect whether the given property exists in the current instance. The property name as a parameter must be specified in string form, such as obj hasOwnProperty("name")

  3. isPrototypeOf(object): used to detect whether the incoming object is the current prototype

  4. propertyIsEnumerable(propertyName): used to detect whether a given property can be enumerated using a for in statement

  5. toLocaleString(): returns the string representation of the object;

  6. toString(): returns the string representation of the object;

  7. valueOf(): returns the string, numeric value or Boolean value display of the object ❓❓❓

    5. All 6 are output [object]

6. Rounding retention

1. parseInt rounding keyword

1.1 decimal rounding
var a=89/5;
c=parseInt(a);//C = rounding of a

1.2. Take the first number of the string
Normal condition
var a="123abc"
var c=parseInt(a);//C = number before a

exceptional case
var a="a12a12"
var c=parseInt(a);//c=NaN

2. Float float

var a="3.14";
var b=parseFloat(a);

The effect is not obvious.

3. Take the decimal places ToFixed:

var a=3.141592453589;
var c=a;
//Keep two decimal places
//The output result is a string
//The output is a string

7. Operation operator

1. Assignment "="

var a=1;

2. Four operations:

+ - * / ++ -- += -= *= /=

Special use
var str="10.1";
str=+str;console.log(str);//At this time, str is converted to Number type, and the minus sign can also be used in this way;

All but + can convert strings containing valid digits to numeric types

3. Character operation (string splicing)

var a="hollo",b="world",c=a+b;console.log(c);//holloworld
var a="a Value of=",b=1,c=a+b;console.log(c);//Value of a = 1

4. Comparison operation (relation operation)

> < >= <= == ===

Ternary operation: a > b? a:b

  • ==(judge whether the values are relative or not, regardless of whether they are of the same type)

  • ===(first judge whether it is of the same type, and then judge whether the values are equal)

    var a=12,b="12";
    console.log(a==b,a===b)//true false

5. Logical operation

& | ! ~ && ||

Bitwise non
var num1=25;
var num2=~num1;

Bitwise AND
var result=25&3;console.log(result);//1

Bitwise OR
var res=25|3;console.log(res);//27

Positional difference
var res=25^3;console.log(res);//26

Shift left
var oldValue=2;//Binary 10
var newValue=oldValue << 5;//1000000 binary, 64 decimal;

Signed right movement
var oldValue=64;//Binary 1000000
var newValue=oldValue >> 5;//Binary 10, decimal 2;

Unsigned right movement
var oldValue=64;//Binary 1000000
var newValue=oldValue >>> 5;//Binary 10, decimal 2;
var oldValue=-64;
var newValue=oldValue >> 5;

Short circuit operation ⭐⭐
var res=true&&false;console.log(res);
var res=true||false;console.log(res);

Can be used to solve compatibility problems

8. Statement

1. If else statement: omitted

2. Do while statement

var  i = 0;
    i += 2;

3. while statement

var i=0;

4. for statement

for(var i=0;i<5;i++){console.log(i);}
for(let i=0;i<5;i++){
    for(let j=0;j<4;j++){
for(;;){console.log("hollo world")}//Infinite loop
//Note that the parameters in for can be proposed, but judgment conditions should be added to stop the cycle

5. For in statement

An iterative statement used to enumerate data traversing object types

for(let i in arr){console.log(i,arr[i])};
for(let key in obj){console.log(key,obj[key])};

Note: null and undefined cannot be used

6. label statement

Using the label statement, you can add labels to your code for future use

start:for(var i=0;i<count;i++){console.log(i);};

7. break and continue statements

  1. break is to end the current statement, and the following statements will no longer be executed;
  2. continue is to skip an execution step and then execute the code of the next step;
  3. outermost in a double for loop, the inner one skips the outer one; (not used)

8. with statement ⭐

var qs=location.search,substring(1);
var hostName=localtion.hostname;
var url=localion.href;
//Use the with statement to bring out the locality for public use
    var qs=search,substring(1);
    var hostName=hostname;
    var url=href; 

9. switch statement

let num=2;
switch(num){//This parameter can be a string or true.
	case num=1:
    case num=2:
    case num=3:

Note: switch has the nature of penetration. If there is no break, it will be executed from top to bottom as long as it meets the case conditions

This property can be used reasonably

10. Function

function fn(){
    console.log("hollo world");
//Deconstruct function call with assignment + default value
function add(num,{a,b},[c,d],e=15){
    //The return result is return
    return num+a+b+c+d+e;
    //Return. All the codes after return will no longer be executed. End of function
console.log(add(1,{a:2,b:3},[4,5])+15);//30 45
//Anonymous functions are called
var fn=function(){};
~function(){}();//I can't use it. I really don't understand

/*****Arrow function*****/
let fn=()=>{};fn();
let fn=res=>console.log(res);fn(20);//Parentheses are not required for a single argument or a single function body
let fn=(a,b)=>a+b;console.log(fn(1,2));//Direct return to a+b

/*****Function default****/
let fn=(a,b=10)=>a+b;console.log(fn(1));

Note: you can access the parameter array of a function through the arguments object,

A function can be assigned and called multiple times without overloading

11. For of statement

The use and effect are the same as for in, but it can't traverse objects and can use arrays

12. Try catch statement

Execute the contents in try first. If an error occurs in the contents of try, then execute the contents in catch.

try {
catch(err) {
    document.getElementById("demo").innerHTML = err.message;

4. Volume, domain, memory

1. Quantity reference

  1. You can only add attributes to reference types, not to base types

  2. When copying or saving a variable, the operation is the reference of the object, but when adding a property or method, the operation is the actual object.

  3. Functions cannot be accessed by reference, but only by value (object special case)

  4. The parameters of a function are local variables of the function

  5. Function parameter passing object

    let obj=new Object({a:1,b:2});
    //Situation 1
    function fn({a,b}){
        return {a,b};
        //The effect of the study is the same whether return is added or not
    //At this time, obj does not change. This is deconstruction assignment, and the function is accessed by value
    //Situation II
    function fn1(obj){
    //At this time, the obj changes. Here, it is accessed by reference
    //Situation III
    function fn2(obj){
        obj=new Object();
        //When the parameter in the function re creates an object, it becomes a local variable and no longer shares an object reference address with the external object. And this object is automatically destroyed after the function is executed ⭐⭐⭐⭐⭐
    //At this time, the a attribute of obj changes, but the name attribute is not added

2. Data type detection:

  1. typeof: omitted

  2. instanceof: check whether the data is of the specified type

    console.log("231" instanceof Array);//false

    Note: all reference type data are instances of Object

  3. console. Dir (element): returns the full details of the element

3. Environment and scope

Execution context:

  1. The window object is considered as the global execution environment (the top object always points to the window object, and the two are exactly the same)

  2. A function body is also an execution environment

  3. After the code in an environment is executed, the environment and variables are destroyed. The global execution environment of window objects is destroyed when the browser is closed

  4. Scope chain and active object

    let color="blue";//Create global variable
    function fn(){

    The function here is called without parameters, but the color variable is used in it. However, if there is no color variable in the internal execution environment of the function, it will look up to the next level until it is in the global execution environment. If there is no color variable in the global environment, an error will be reported.

    function fn(){
        var color="red";

    At this time, a color variable is created in the function execution environment, but it can be used in the global environment (except return ing the variable). All cannot output the color variable in the global environment, and the color variable is destroyed after the function is executed.

  5. Delay scope chain 🌙

    The principle is that some statements temporarily add a variable object at the front end of the scope chain, and the variable object will be removed after code execution.

    • Catch block of try catch style
    • with statement


  6. No block level scope

    That is, the variables from var in if and for styles can be used globally, but not functions

4. Garbage collection

1. Introduction

javaScript has an automatic garbage collection mechanism.

Principle: find out those variables that are no longer used, and then release the memory occupied by them. There is a time interval and periodicity.

  1. Method 1: Mark clearing
  2. Mode 2: application counting

Performance issues: the short garbage collection cycle of IE browser leads to frequent garbage collection, which is the infamous performance prototype of IE6. IE7 rewrites the garbage collection mechanism.

2. Use

Call window The collectgarbage() method performs garbage collection immediately

3. Manage

Dereference: once the data is no longer used, it is best to release its reference by setting its value to null.

Function: it is convenient for the garbage collection mechanism to clear it next time

5. Reference type (method set)

It is often called class or object definition, but it is not the same concept as class

Due to the lengthy introduction in the official, the dry goods are delivered directly

Type detection is in Chapter 4

1. Object type

1. Examples

var person = new Object();
var person = {
        console.log('can't afford to eat sth.');

2. Properties and methods

var age=20;
person.age;//Relatively special

    console.log('have a good appetite');
//Properties and methods are overwritten writes, that is, modify and reset
//The newly added property name or method name cannot be duplicate

delete person.age//Delete a property
//There is no length attribute to read the length ⭐⭐⭐

3. Property read

person.eat();//Call a property's method

var str='name';
var nume=person.name;
var userName=person['name'];
var theName=person[str];
//These three variables store the same data

4. Object conversion array

1. Generate an array of property names:


2. Generate an array of property values:


5. Traversal

Traversal can use the for in traversal method

for in traversal method

for(let i in obj){
//The string of each attribute of obj stored in each i at this time

6. JSON conversion

It can be used as long as it comes from an Object instance

  1. let str=JSON.stringify(obj) object to string
  2. let obj=JSON. STR objects to strings

7. Deconstruction assignment ⭐

var {a,b,c=3}={a:2,b:3};
const a=1;
const obj={a,b:2,c:5};

8. Expand merge

let obj={a:1,b:2};
let oaj={...obj,c:4,d:5};//Expand obj

2. Array type

1. Examples

let arr=new Array();
let arr=[];
//Note that if there is only one value in Array(), the length of the array is defined as this value
let arr=[1,2,3];
let arr=new Array(1,'hollo world',{name:'jack'});
let arr=[1,'hollo world',{name:'jack'}];

2. Array reading

console.log(arr[0]);//The index of the first element of the array is 0

3. Length of array

let len=arr.length;//Use the length attribute to get the length
//If the array length is set to be less than the original length, the element data with the difference will be deleted. If it is greater than the original length, an undefined supplement will be added

4. Array method

  • array.splice(Who starts,Number of deleted[,Replacement 1,Replacement 2,...]);
  • array.push(New element);//Add from last
  • array.pop();//Delete last
  • array.unshift(New element)//Add from scratch
  • array.shift();//Delete one from scratch
  • array.sort();//Elements are sorted by ASCII code from small to large
  • array.sort(function(a,b){return a-b});
    //Elements are sorted by value from small to large
  • array.sort(function(a,b){return b-a});
    //Elements are sorted by value from large to small
  • array.reverse();//Reverse array
  • array.concat(Another array);//Splice another array behind the array
  • array.join('character');//Add 'character' between elements and return string
  • array.toString();//Convert array to string
  • array.slice(Who starts,Which end);
    //Read the specified position, including the start position and excluding the end position
  • array.indexOf(element);
    //Find the position subscript of the element for the first time from the beginning, and the element does not exist. Go back to - 1;
  • array.lastIndexOf(element);
    //Find the position subscript of the element for the first time from the tail, and the element does not exist. Go back to - 1;
  • array.forEach(function(v,i,array){
        //Function body,
    //Parameter 1: element; Parameter 2: subscript; Parameter 3: current array;
    //Used to traverse an array
  • array.every(function(v,i,array){
        //Judgment function body
    //Judge whether each element meets the condition of true, otherwise judge whether all elements meet the condition of false
  • array.some(function(v,i,array){
        //Judgment function body
    //Judge whether each element meets the judgment conditions. If one element meets the anti true condition, all elements will be anti false
  • array.map(function(v,i,array){
        //Function body
    //Each element of the array is changed and a new array is generated, and the original array remains unchanged
  • array.filter(function(v,i,array){
        //Judgment function body
    //Filter the elements that meet the judgment conditions and return a new array, and the original array remains unchanged
  • array.find(function(v,i,array){
        //Judgment function body
    //Filter the elements that meet the judgment conditions, find and return the first element, and return false if not found
  • array.findindex(function(v,i,array){
        //Judgment function body
    //Filter the elements that meet the judgment conditions, find and return the subscript of the first element, and return - 1 if not found
  • array.include(v);//Judge whether the array contains v and inverse Boolean value

5. Traversal of array

You can use for in traversal, and it is easier to use forEach and other methods

6. Deconstruction assignment

const [a,b,c,d=8,[e,f]]=[1,2,3,5,[6,8]];

7. Expand merge

//About to arr expand
let fn=(...arr)=>console.log(arr);//Combine numbers into an array

3. Data time type

UTC international coordinated time

1. Get time

A time object is created

let data= new Data();//Get current time
let data=new Data("2015-2-18");//Gets the specified date
let data=new Data("2015-2-18 06:05:52");//Gets the specified time and date
let data=new Data(1543499394644);//Gets the specified timestamp time
let data=+new Data();//Get the current timestamp

You can also get the specified time through the created data object. This method is not commonly used

data.parse("2015-2-18 06:05:52");//Gets the specified time and date
data.UTC(1543499394644)//Gets the specified timestamp time

2. Processing time

Obtain the time period by obtaining the time difference between the current time before and after different times

3. Time formatting

  1. toDateString() - displays the day of the week, month, day, and year in an implementation specific format
  2. toTimeString() - displays the hour, minute, second, and time zone in an implementation specific format
  3. toLocaleDateString() - displays the day of the week, month, day, and year in a region specific format
  4. toLocaleTimeString() - displays the hours, minutes, and seconds in an implementation specific format
  5. toLocaleString() - – - displays UTC dates in an implementation specific format

4. Time object method

1. Get time starts with get
//They are all return values, and the timestamp is the number of milliseconds
data.getTime();//Time to milliseconds
data.setTime();//Millisecond revolution time
data.getFullyear();//Take 4 as the year
data.getUTCFullYeat();//The year turns to milliseconds, and the UTC date is obtained as long as UTC is added after it
data.getMonth()//; Get the month. Note that the return value is 1 less than the current month
data.getDate();//get date 🌙
data.getDay();//Get week 🌙
data.getHours();//Get hours
data.getMunutes();//Get minutes
data.getSecinds();//Get seconds
data.getSeconds();//Get milliseconds
//Difficult to use
data.getMilliseconds();//Number of milliseconds in date
data.getTimezoneOffset();//Returns the minute difference between local time and UTC time

2. Set / modify time starts with set

Replace get with set, and the method changes from the return value to the set value

5. Time localization

let allTime=data.toLocalString();//Full localization
let dateTime=data.toLocalDateString();//Localization date only
let Time=data.toLocalTimeString();//Localization time only

4. RegExp regular type

1. Regular expression writing

let reg=/Regular body/[sign];
let reg=/at/g;
let reg=new RegExp(/at/i);

2. Sign

  1. g: Global mode, which applies to all characters of the checked string and returns the first one when found
  2. i: Case insensitive
  3. m: Multiline mode

Can write together

let reg=/at/gi

3. Regular metacharacter

  1. Matching number: \ d
  2. Match any non numeric character: \ D
  3. Match letters or numbers or underscores: \ w
  4. Matches any character other than letters, numbers, underscores: \ W
  5. Match any whitespace: \ s
  6. Match any character that is not a blank character [^ note 1]: \ S
  7. Match any single character except newline:
  8. Indicates the text that matches the beginning of the line (starting with whom) [Note 2]:
  9. Indicates the text that matches the end of the line (end with whom) [^ note 3]:$

4. Regular qualifier

  1. Repeat zero or more times:*
  2. Repeat one or more times:+
  3. Repeat zero or once:?
  4. Repeat n-1 times: {n}
  5. Repeat n or more times: {n,}
  6. Repeat n to m-1 times: {n,m}

5. Regular others

  1. The string is enclosed in square brackets to match any of the characters, which is equivalent to or: []
  2. Match content except brackets: [^]
  3. Escape character:\
  4. Or, choose one of the two. Note that the left and right sides are divided into two parts, regardless of how long and messy the left and right sides are: | example: let reg = / (male | female) /;
  5. Select one of the two direct quantities and group [^ note 4]: ()
  6. Matching Chinese characters: [\ u4e00-\u9fa5]
  7. Parentheses (): matches the string in parentheses, which can be one or more. It is often used with the "|" (or) symbol. It is a multi-choice structure

6. # regular use ⭐

  1. Match - regular expression Test (string); Inverse Boolean

  2. Find - string Search (regular); Filter the part that meets the conditions, inverse subscript, no result, - 1;

  3. Extract - string Match (regular); Extract the part that meets the conditions and invert the array;

  4. Extract - regular Exec (string); Extract the first and inverse results that meet the conditions;

  5. Replace - string Replace (regular, new content); Replace regular content with new content

  6. Fuzzy Lookup - string Search (regular);

    var text='cat bat sat fat';
    var pos=text.search(/at/);//Returns the position where at first appears, and returns - 1 if none
    console.log(result);//Find at position, replace from word(.at)
  7. Reference substitution

    var str = '8/1/2019';
    var reg = /(\d)\/(\d)\/(\d+)/;
    var res = str.replace(reg,"$3/$1/$2");

7. Official supplement

var text='this ha a short summer';
var pattern=/(.)hort/g;
    console,log(RegExp.input);//this has been a short summer
    console,log(RegExp.leftContext);//this has been a
input Returns the original string
leftContext Return to the left of the result
rightContext Returns the to the right of the result
lastMatch Return results
lastParen Returns the number of parentheses that match the captured
 The last one failed 😅

5. Function type

1. No overload

Is the function duplicate name coverage.

2. A pit

var sum=function (){
//sum is not function
function fn(){
//No error will be reported at this time

3. Function as value

In ECMAScript, the function itself is a variable, which means that a function can also be used as a value

4. Function internal properties

1. arguments property,

I haven't seen it, I haven't used it, and an error is reported in strict mode. Recursive function

function fn(n){
        return 1;
        return n*fn(n-1);
function fn(n){
        return 1;
        return n*arguments*callee(n-1);

The explanation is that such rewriting can release the close coupling between function execution and function name fn

2. this attribute

The pointer in the function points to window by default.

When binding an event, it usually points to this event. However, the function triggered by the event function does not point to this event. You can modify (jump) through call, apply and bind in es6

3. Change the direction of this

Function: they all change the direction of this, but the forms of parameters are different

1. call method

Function: call this function and modify the direction of this in the function

Detailed explanation of parameters:

The first parameter: write whoever this points to in the function

Subsequent parameters: the arguments to be passed in by the called function, separated by commas

2. apply method

Function: call this function and modify the direction of this in the function

**Syntax: * * function name Apply (object, array);

Detailed explanation of parameters:

The first parameter: write whoever this points to in the function

The second parameter: pass in an array to store the arguments required by the called function

3. bind method

Function: without calling the function, clone a new function, modify the direction of this in the new function, and return the new function

**Syntax: * * function name Bind (object [, argument]);

Detailed explanation of parameters:

The first parameter: write whoever this points to in the function

Subsequent parameters: the arguments to be passed in by the called function, separated by commas

3. prototype construction

Function name prototype() access function prototype

4. Function packaging

Outside the code, there is a well-known function that is not called. Set the required parameters to this well-known parameter, and the code is encapsulated.

5. Deconstruction assignment

function fn({a,b}){

6. boolean type

6 +, number type

  1. Method of formatting numerical value: toExponential(), convert to e notation
  2. toFixed(), toPrecision(), to be checked

7. string type

Direct methods are all return values. String regular methods have been listed in the regular introduction.

str.charAt(subscript);//Find subscript position character
str.charCodeAt(subscript);//ASCII code for finding subscript position characters
str.concat(Another string);//Append a string. Do not use this property. Use+
//The second parameter of the following three methods can be negative.
str.slice(Start position,End position);//Intercept from the start position to the end position, excluding the end position
str.substring(Start position,End position);//Intercept from the start position to the end position, excluding the end position
str.substr(Start position,Number of interceptions);//Intercept the specified number from the starting position
str.indexOf("s");//The first subscript position of s in the character is queried from the beginning, and anti-1 is not found;
str.lastIndexOf("s");//Query the first subscript position of s in the character from the tail, and anti-1 is not found;
str.trim();//Clear the extra space on both sides of "o o", and the space in the middle cannot be cleared
str.toUpperCase();//Character to size
str.toLowerCase();//Character to lowercase
/*Contains two unusual
toLocaleUpperCase();And tolocalelovercase();
It is used in specific areas, such as (Turkish)
//split returns a numeric value
//Split the string with comma "," and [get the specified number] and splice it into a numerical value in the same order
str.split(regular[,number]);//Crack with regularity.

str.localeCompare(Column string);//Compare the size of the asicll code of the first character, which is not commonly used
String.formCharCode(asicll code[,Multiple values can be filled in]);//Return string to clasil
str.startsWith("character");//Judge whether it starts with "character" and return Boolean value
str.endsWith("character");//Judge whether it ends with "character" and return Boolean value
str.include("character");//Judge whether it contains "character", inverse Boolean value

//Encrypt string   
function compileStr(code){
    var c=String.fromCharCode(code.charCodeAt(0)+code.length);  
    for(var i=1;i<code.length;i++){        
    return escape(c);
//Decrypt string   
function uncompileStr(code){
    code = unescape(code);        
    var c=String.fromCharCode(code.charCodeAt(0)-code.length);        
    for(var i=1;i<code.length;i++){        
    return c;

8. Golbal object

Golbal (global) object is the most special object, an object that doesn't exist at all

1. Encoding and decoding of url

Encode the URL through encodeURL() and encodeURLComponent()

var uri="http://www.wrox.com/illegal calue.htm#start";
//The result is:“ http://www.wrox.com/illegal  calue. htm#start"
//The result is:

The first one won't encode the special characters of the URL, the second one will, but the second one is confidential

The corresponding decodes are decodeURL() and encodeURLComponent()

2. Online compilation of eval method

Establish a JavaScript running area and directly run js code. Online compilation is completed in this way.

//This code is equivalent to

Try not to use this method to receive data, otherwise malicious code input, code injection, will occur

3. It's all prototypes

Is the prototype of all constructors, that is, it is null, and undefined, none, Object, Array and so on are its properties. The relationship between window and it is very vague. I can't understand it. I need to query the information in addition

9. Math object

Add Math to the front

Math.random();//This is a random number assigned to a variable

All return values

1. Value

EReturns the arithmetic constant e, which is the base of the natural logarithm (approximately equal to 2.718).
LN2Returns the natural logarithm of 2 (approximately equal to 0.693).
LN10Returns the natural logarithm of 10 (approximately equal to 2.302).
LOG2EReturns the logarithm of e based on 2 (approximately equal to 1.4426950408889634).
LOG10EReturns the logarithm of e based on 10 (approximately equal to 0.434).
PIReturns the PI (approximately equal to 3.14159).
SQRT1_2Returns the reciprocal of the square root of 2 (approximately equal to 0.707).
SQRT2Returns the square root of 2 (approximately equal to 1.414).

2. Method

abs(x)Returns the absolute value of x.
acos(x)Returns the inverse cosine of x.
asin(x)Returns the arcsine value of x.
atan(x)Returns the arctangent of x as a number between - PI/2 and PI/2 radians.
atan2(y,x)Returns the angle from the x-axis to the point (x,y) (between - PI/2 and PI/2 radians).
ceil(x)The logarithm is rounded up.
cos(x)Returns the cosine of a number.
exp(x)Returns the index of Ex.
floor(x)Round down x.
log(x)Returns the natural logarithm of a number (base e).
max(x,y,z,...,n)The highest value of X, Z.
min(x,y,z,...,n)Returns the lowest value of x,y,z,..., n.
pow(x,y)Returns the y-power of x.
random()Returns a random number between 0 and 1.
sin(x)Returns the sine of a number.
sqrt(x)Returns the square root of a number.
tan(x)Returns the tangent of the angle.

10. Enumeration Technology

Enumeration is done through objects

const jieHunEnum={
if(obj.isJieHun){//obj object from outside
//Through obj Deconstruct and assign the 1 / 2 value returned by isjiehun

const arr=["1","2"];
const hobbyEnum={
    "3":"Bubble sister"
const brr=arr.map(v=>hobbyEnum[v]).join(",");
//Through the map method, iterate through the enumeration to process the value of the arr array, return a new array, and then join it.

6. Object oriented programming

One sign of object-oriented languages is that they all have the concept of class

The following is different from the official content. Here is the summary of operation methods to avoid complex principles. You need to consult materials.

Introduction to medicine: the classic problem of elephants entering the refrigerator

Process oriented:
I opened the door of the refrigerator, I loaded the elephant in, and finally I closed the door of the refrigerator. I was working all the time.
I ordered the refrigerator door'Door open',Let the refrigerator door open by itself. I ordered the elephant'Put it in',Let the elephant put itself in the refrigerator. I ordered the refrigerator door'The door closes',Let the refrigerator door close by itself. The whole process I only command, not work. I face the door of my refrigerator and the elephant is working
 Myth: elephants and refrigerators must be pure objects. How to command without objects? And elephant and refrigerator work is its internal method.

1. Object operation method settings

  1. Configurable: indicates whether the attribute can be deleted through delete to redefine it. The default value is true
  2. Enumerable: indicates whether the for in loop can be used. The default is true
  3. Writable: indicates whether the value of the attribute can be modified. Default true
  4. Value: indicates the default value of an attribute, which is undefined by default
  5. Get: the function called when reading the property. It is underfunded by default
  6. Set: the function called when writing the attribute. It is underfunded by default
let person={
    Object.defineProperty(person,"name",{//What is this defineProperty?
    	writable:false,//Change writable to false
person.name='rose';//It will be ignored in the non strict mode, and an error will be reported in the strict mode

2. New method

  1. defineProperties(): define multiple properties
  2. configurable
  3. enumerable
  4. get and set
var book={};
            return this.name;

3. Factory mode

It is to use function to write a constructor, also known as factory function, which can create the same objects in large quantities

Constructor considerations:

  1. Constructors are inherently used to create objects, so they must be used in conjunction with new, or they will not have the ability to create objects
  2. The return keyword cannot be inside the constructor, because the constructor will automatically return the object. If you return a basic data type, as with no effect, if you return a complex data type, the constructor is meaningless.
  3. If the parameter is not required for new, the parentheses can be omitted
  4. People usually capitalize constructors

The constructor at this point has a disadvantage:

Method takes up memory and causes waste

This is the biggest problem with native objects

function Fn(name,age){
        console.log("have a good appetite");//Occupy memory
let fn=new Fn("jack",20);

be careful: ⭐⭐⭐⭐⭐

Serious factory function

function Person(){

4. Prototype mode

Add the prototype prototype of the constructor to the public function, so that the instantiated object can use the public function without wasting memory.

/Set the edible function on the prototype
fn.protorype.eat=function(){console.log('have a good appetite');};

1. Relation diagram

2. in operator ⭐

Check whether a property is in the object and return Boolean value

let obj={'name':'jack'};
console.log('name' in obj);//The result returns true

The property set on the prototype also returns true

function Fn(){
let fn=new Fn();
console.log('age' in fn);

Extended application: obj getOwnPropertyNames(),obj. The upgraded version of keys () can be used whether enumeration is possible or not.

3. Simpler prototype statement

function Person(){

4. Dynamics of prototype

Is the price method function in operation

Person.prototype.fn=function(){console.log('I'm dynamic');};

5. Parasitic mode

Create an object in the constructor, then set the object and return it

function Person(name,age){
	var obj=new Object();
	return obj;
var jack=new Person('jack',20);

Not recommended

6. Safe constructor mode

There is almost no difference between structure and parasitism, so it is not recommended

7. Inherit

1. Prototype chain

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-5rVfLzhR-1622042557060)(F: \ note file \ media \ 156648554743. PNG)]

That is, the instance object passes__ proto__ A chain of upward access; obj.__proto__ The value of is the obj prototype

2. Prototype inheritance

//This is archetypal inheritance
/Inheritance 1: use prototype inheritance to assign the instance object of the parent class to the prototype object of the child class
function Animal(){
    this.status=()=>{console.log('Rich man');};
var animal=new Animal();
function Dog(name){//Mom (constructor)
Dog.prototype=animal;//Dad is a rich man. Dad has a showdown. Dad is the prototype
//But Dad forgot his mother, that is, the prototype has no constructor
var ha=new Dog('Siberian Husky');//This is a grandson's

3. Borrowing function inheritance

//Borrowing function inheritance
function Animal(){
Animal.prototype.eat=function(){console.log('How rich');}//Can't inherit money

function Dog(name){
    Animal.call(this);/⭐Copy function, Dad lied that he was rich, but he had no money
var ha=new Dog('Siberian Husky');
// ha.eat();  // Error reporting

Using borrowing functions to implement class inheritance can only access the properties of the parent class, not the methods on the prototype of the parent class ⭐

4. Hybrid inheritance

function Animal(){
    this.pa='Rich man';
Animal.prototype.eat=function(){console.log('have a good appetite');}
function Dog(name){
//"= this fast is the constructor, mom
Dog.prototype=new Animal();//Dad had a showdown
Dog.prototype.constructor=Dog;//Dad doesn't remember his mother. Let him remember his mother, that is, point the constructor of the prototype to the original constructor again
var ha=new Dog('Siberian Husky');
/Hybrid inheritance,Borrow the function to inherit once, and use the prototype to inherit again

5. Parasitic inheritance (abandonment)

8. class of ES6

1. Grammar

It's short for function and prototype

class Animal{
    /Both properties and methods are written in this bracket
    /That is, No prototype
    /One entry: method/function-constructor
        /Use the same method as constructor
        this.eat();/Direct call eat Function without calling the object after creating the object.
    eat(){/This binds the method to the prototype and implements it prototype Function of
        console.log('Hunger and thirst');
var animal=new Animal('zs',20);

2. Inherit

/Explicit inheritance syntax:

class Subclass extends Parent class{
class Car{
        console.log('Run fast');

class Wow extends Car{
        super();//This is just needed without error reporting. The function generates a this and points to the parent class
        /super Must be in the first position
      /You can also completely avoid the parent class, that is, in constructor Manually return an object inside(return obj)
var car=new Wow('911')
/Syntax stipulates that a class can only inherit one class, not multiple

3. super example

class Gad{
        this.god='King Xu'
class people extends Gad{
// class people {
        super(name)/This adds a pointer to the parent class this,Pass parameters to parent class
var peo=new people('Xu')

7. Function expression

1. Recursion

A function calls itself by name

2. Closure

1. Common words:

Function sets form closures!

2. Introduction:


A small function is returned inside the large function, which is received by the variables outside the large function, and the small function uses the variables in the large function.

3. Features:

  1. A function is returned in the function so that large functions can be obtained in the whole world and small functions can be obtained.
  2. Small functions can change the data in large functions, and this data can be persistent rather than destroyed every time it is called

This form of code is called closure.

In general, every time a function is called, the variables in it will restart, but the closure will not, because the closure space will not be destroyed.

4. Advantages:

  1. The scope space is not destroyed, so the variable will not be destroyed, which increases the declaration cycle of the variable

  2. Variables inside the function can be accessed outside the function

  3. Protect private variables and define variables in functions without polluting the global environment

  4. You can make the function execute only once and use it when the event is triggered multiple times

    function fn(s){
        return function fs(){
    let f=fn("javascript");

5. Disadvantages:

  1. Because it is not destroyed, it will always occupy memory. If it is too much, it will lead to memory overflow
  2. Because the variables inside the function can be accessed outside the function, the reference relationship between the variables and the internal function always exists, and the memory cannot be destroyed
  3. It is not particularly convenient to use closures to access

6. To be verified: the principle of closure formation

  1. Function returns the basic data type. After it is used up, the data will be destroyed.
  2. Function returns complex data types. After it is used up, the data will not be destroyed.

7. Change to closure

A function shell can also be set outside, a return can be added to the head, or let can create variables.

8. Note that this points to

this in the closure points to something strange. Be careful and interrupt the output more. Check it

3. Mimic block action level

It is to simulate a private scope by using the scope principle of function

function fn(n){
        for(var i=0;i<n;i++){
    console.log(i);/report errors, i is undefined,That is, variables in the simulated private scope cannot be accessed

4. Private variable

Or the variables inside the function do not return or call out, and no one outside can use them.

5. Privileged method

Public methods that have access to variables and functions are called privileged methods

1. Defining privileged methods in constructors

function MyObject(){/Constructor
    /Using variables and private functions
    var able=10;
    function active(){
        return false;
    //privileged method 
        return active();

At this time, private variables can only be accessed through the action attribute of the instantiated object of the constructor

Using usage and privileged members, you can hide data that should not be modified directly, for example; (in this way, you can create a real encapsulation, like jQuery)

function Person(name){
        return name;
var person=new Person('jack');

2. Static private variable

    var num=10;//private variable
    function able(){//Private function
        return false;
    /Define public methods on constructor prototypes
        return able();

This method is an improved and upgraded version of the previous method, which solves the problem of memory waste of constructors.

3. Module mode (single example)

A constructor can only create one object in heap space. The objects from the constructor instance are equal.

Normal constructor

function Person(){}
let n1=new Person{};
let n2=new Person{};
//That is, two objects are created in heap space

Implementation singleton (closure)

let fn=function(name){
    function Per(name){//Constructor
    let obj;//initialization
    return function(name){//Return closure function
        if(obj){//Judgment initialization
            return obj;
            obj=new Per(name);
        return obj;
let a=fn('rose');//Create object a with function
let b=fn('jack');//Create object b with function


The core of BOM is window object

1. Window relationship and framework (difficult)

The frame is to use the < frames > single label to create a new frame in the frame double label to divide the browser window. For example:

<html lang="en">
<frameset cols="25%,50%,25%">
  <frame src="frame_a.htm">
  <frame src="frame_b.htm">
  <frame src="frame_c.htm">

Each framework has its own window object, which is saved in the farms collection. In the collection, the corresponding window object can be accessed through the index,

Get frames to reference the framework, and use the top object. The top object always points to the frame of the most (outermost) layer

For example, top frames[0]**

**Note: the top object is all equal to the window object

Another window object opposite top is parent. The parent object always points to the immediate upper frame of the current frame. In some cases, parent may be equal to top. In the absence of a framework, parent must be equal to top, that is, both are equal to window

2. Window position

1. screenLeft/screenTop

Is a property used to determine and modify the location of window objects

Use the following code to get the position of the left and top of the window across browsers, so as to solve the compatibility problem

var leftPos=(typepf window.screenLeft==='number')?window.screenLeft:window.screenX;
var topPos=(typepf window.screenTop==='number')?window.screenTop:window.screenY;

This property is used in some browsers and is not recommended


moveTo() receives the x and y coordinate values of the new location, and moveBy() receives the number of pixels moved horizontally and vertically

window.moveTo(0,0);//Move the window to the upper left corner of the screen
window.moveBy(-50,100);//Move the window 50px left and 100px down

3. Window size

It is a complex problem, quite complex problem, all kinds of compatibility, compatibility of different versions, compatibility of different manufacturers and compatibility of different modes

IE9+,Safari,Firebox,adopt outerWidth and outerHeight Returns the size of the browser
Opear But I have to pass innerWidth and innerHeight Returns the size of the browser
Chrome Both can be used
ie6 yes document.documentElement.clientHeight and document.documentElement.clientWidth And in standard mode,
Hybrid mode yes document.body.clientHeight and document.body.clientWidth

For mobile terminal development, it is recommended to read: Mobile Web development

In addition, resizeTo() and resizeBy() can be used to resize the browser window.

window.resizeTo(100,100);/Adjust to 100 x100
windiw.resizeBy(100,50);/Adjust to 200 x150

**Note: * * it's OK to use this directly (including scroll bar)

  1. Height of browser window:
let h=window.innerHeight;
  1. Width of browser window:
let w=window.innerWidth;

4. Browser navigation information

1,window.open() method

/Equivalent to<a href='http://www.baidu.com' target='topFrame'></a>


Optional. Opens the URL of the specified page. If no URL is specified, a new blank window opens

  • _ Blank - the URL is loaded into a new window. This is the default
  • _ Parent - the URL is loaded into the parent frame
  • _ self - URL replaces the current page
  • _ URL set loadable - Top
  • Name - window name


Optional. A comma separated list of items. Support table binary

channelmode=yes|no|1|0Whether to display window in theater mode. The default is none. Internet Explorer only
directories=yes|no|1|0Whether to add a directory button. The default is yes. Internet Explorer only
fullscreen=yes|no|1|0Whether the browser displays full screen mode. The default is none. The window in full screen mode must also be in theater mode. Internet Explorer only
height=pixelsThe height of the window. minimum. The value is 100
left=pixelsThe left position of the window
location=yes|no|1|0Whether to display the address field The default value is yes
menubar=yes|no|1|0Whether to display the menu bar The default value is yes
resizable=yes|no|1|0Whether the window can be resized The default value is yes
scrollbars=yes|no|1|0Whether to display the scroll bar The default value is yes
status=yes|no|1|0Do you want to add a status bar The default value is yes
titlebar=yes|no|1|0Whether to display the title block Ignored unless calling an HTML application or a trusted dialog box The default value is yes
toolbar=yes|no|1|0Whether to display the browser toolbar The default value is yes
top=pixelsThe position of the top of the window Internet Explorer only
width=pixelsThe width of the window minimum. The value is 100


Optional. Specifications specifies whether the URL loaded into the window creates a new entry in the window's browsing history or replaces the current entry in the browsing history. The following values are supported:

  • True - the URL replaces the current entry in the browsing history.
  • False - the URL creates a new entry in the browsing history.


Close browser window: window close()

Only applicable to window Open() to open a pop-up window, you can use top Close() closes the window without the user's permission

6. Pop up screen

By detecting window Whether open() is null determines whether the pop-up window is hidden

5. Intermittent call and timeout call

This is the timer. Note that the timer is asynchronous

  1. Timer: setinterval (function executed, interval time)

  2. Timer: setTimeout (function executed, time delayed)

  3. End timer: (it can be mixed and stopped)

    1. clearInterval(timerId)
    2. clearTimeout(timerId)

7. Browser dialog information

The browser dialog boxes are alert(), confirm(),prompt(), and print()

When the dialog box pops up, the code will stop executing. Close the dialog box and the code will continue executing

Use the return value of confirm() to judge the user selection of the confirm() dialog box

Use the return value of prompt() to obtain the information entered by the user in the dialog box

8. location object ⭐

hashReturns the anchor portion of a URL
hostReturns the host name and port of a URL
hostnameReturns the host name of the URL
hrefReturn full URL
pathnameThe returned URL pathname.
portReturns the port number used by the URL server
protocolReturn a URL protocol
searchReturn the query part of a URL (? And the following content, that is, the request information of git) ⭐

Assignable output, settable

This can be used to obtain the information transmitted by git ⭐


Jump to Baidu

Current output URL All strings

assign()Load a new document
reload()Reloading the current document is refresh
replace()Replace the current document with a new one

9. Navigator object

appCodeNameReturns the code name of the browser
appNameReturns the name of the browser
appVersionReturns the platform and version information of the browser
cookieEnabledReturns a Boolean value indicating whether cookie s are enabled in the browser
platformReturn to the operating system platform on which the browser is running
userAgentReturns the value of the user agent header sent by the client to the server

1. Detect browser plug-ins

Use navigator Plugins value to achieve this

  • Name: plug in name
  • Description: description of the plug-in
  • filename: the file name of the plug-in
  • length: the number of MIME types processed by the plug-in

navigator.plugins: name of a parameter to be detected by the plugin

10. Screen object properties

availHeightReturns the height of the screen (excluding the Windows taskbar)
availWidthReturns the width of the screen (excluding the Windows taskbar)
colorDepthReturns the bit depth of the palette on the target device or buffer
heightReturns the total height of the screen
pixelDepthReturns the color resolution of the screen (bits per pixel)
widthReturns the total width of the screen
onLineJudge whether the network is connected. Yes, no, false

11. History object

lengthReturns the number of URLs in the history list


back()Load the previous URL in the history list
forward()Load the next URL in the history list
go()Load a specific page in the history list. Positive is forward and negative is backward

9. Client detection 🌙

It's just a bunch of compatibility problems. It's a lot of trouble. It's hard to understand and sort out. Don't update first

10. DOM and extensions

1. node object properties

baseURIReturns the absolute base URI of the node.
childNodesReturns the node list of the child nodes of the node.
firstChildReturns the first child node of the node.
lastChildReturns the last child node of the node.
localNameReturns the local part of the node name.
namespaceURIReturns the namespace URI of the node.
nextSiblingReturns the node immediately after the element.
nodeNameReturns the name of the node, depending on its type.
nodeTypeReturns the type of the node.
nodeValueSets or returns the value of the node, depending on its type.
ownerDocumentReturns the root element of the node (document object).
parentNodeReturns the parent node of the node.
prefixSets or returns the namespace prefix of the node.
previousSiblingReturns the node immediately before the element.
textContentSets or returns the text content of a node and its descendants.

Several more important

nodeTypeNode type, corresponding value, online query
nodeNameNode name
nodeValueNode value, mostly used for input tag

2. Node object method

appendChild()Add the new child node to the end of the child node list of the node.
cloneNode()Clone nodes.
compareDocumentPosition()Compare the document locations of the two nodes.
getFeature(feature,version)Returns a DOM object that executes a specialized API with a specified feature and version.
getUserData(key)Returns the object associated with the key on the node. This object must first be set to this node by calling setUserData with the same key.
hasAttributes()If the node has an attribute, it returns true; otherwise, it returns false.
hasChildNodes()Returns true if the node has child nodes; otherwise, returns false.
insertBefore()Insert a new child node before the existing child node.
isDefaultNamespace(URI)Returns whether the specified namespace URI is the default.
isEqualNode()Check whether the two nodes are equal.
isSameNode()Check whether the two nodes are the same node.
isSupported(feature,version)Returns whether the specified attribute is supported on this node.
lookupNamespaceURI()Returns the namespace URI that matches the specified prefix.
lookupPrefix()Returns a prefix that matches the specified namespace URI.
normalize()Put all Text nodes under nodes (including attributes) into a "standard" format, in which only structures (such as elements, comments, processing instructions, CDATA sections and entity references) separate Text nodes. For example, there are neither adjacent Text nodes nor empty Text nodes.
removeChild()Delete child nodes.
replaceChild()Replace child nodes.
setUserData(key,data,handler)The key that associates the object to the node.

3. Node relationship

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Coyvys7R-1622042557063)(F: \ note file \ media\timg.jpg)]

4. Get relationship node

  1. Get all child nodes: childNodes
  2. Get all child element nodes: children
  3. Get the first child node: firstChild
  4. Get the last child node: lastChild
  5. Get the first child element node: firstElementChild
  6. Get the last child element node: lastElementChild
  7. Get the next sibling node: nextSibling
  8. Get the previous sibling node: previousSibling
  9. Get the next element sibling node: nextlementsibling
  10. Get the previous element sibling node: previousElementSibling
  11. Get parent node: parentNode
  12. Get parent element node: parentElement
  13. Number of child elements returned by elementcount; No text and comments
  14. Judge whether there are child nodes: parent nodes Contains (child node); true is returned, false is not returned

5. Node operation

  1. ⭐ Create element node: document If the createElement (element label) is below IE7, there will be compatibility problems with the form
  2. Create text node: document createTextNode("<i>hollo world</i>")
  3. Create attribute node: document Createattribute (element attribute) [Note 1]
  4. Create text node: document CreateTextNode (text content)
  5. Insert node at the end: parent node AppendChild (new node added)
  6. Head insert node: parent node InsertBefore (new node, existing point)
  7. Replace node: parent node Replacechild (new node, old element);
  8. Copy node: the point to be copied CloneNode (true (deep copy) / false (shallow copy)); [^ note 2]
  9. Delete node: parent element Removechild (node to be deleted);
  10. Clear all nodes in the parent element: parent element innerHTMML('');
  11. Node merging: parent element normalize(): merge the child elements together (standardize the format)
  12. Split node: parent element splitText(): similar to splitting strings
  13. Class name operation: node className = 'class name'; The assignment can be obtained and modified
  14. Add class name: node classList.add("class name"); Append a class name
  15. Delete class name: node classList.remove("class name"); Remove the specified class name
  16. Switch class name: node classList.toggle("class name"); Add delete switch
  17. Judge whether it contains such name: node classList.contains("class name"); Returns true if any, and returns false if none

6. Doument type

1. Document object properties

asyncSpecifies whether the download of XML files should be processed asynchronously.
childNodesReturns the node list of the document's child nodes.
doctypeReturns the Document Type Declaration (DTD) related to the document.
documentElementReturns the root node of the document.
documentURISets or returns the location of the document.
domConfigReturns the configuration used when normalizeDocument() is called.
firstChildReturns the first child node of the document.
implementationReturns the DOMImplementation object that processes the document.
inputEncodingReturns the encoding method used for the document (when parsing).
lastChildReturns the last child node of the document.
nodeNameReturns the name of the node (depending on the type of node).
nodeTypeReturns the node type of the node.
nodeValueSets or returns the value of the node (depending on the type of node).
strictErrorCheckingSets or returns whether to force error checking.
xmlEncodingReturns the XML encoding of the document.
xmlStandaloneSets or returns whether the document is standalone.
xmlVersionSets or returns the XML version of the document.

2. Document object method

adoptNode(sourcenode)Select a node from another document to this document, and then return to the selected node.
createAttribute(name)Create an attribute node with the specified name and return a new Attr object.
createAttributeNS(uri,name)Creates an attribute node with the specified name and namespace and returns a new Attr object.
createCDATASection()Create a CDATA section node.
createComment()Create an annotation node.
createDocumentFragment()Create an empty DocumentFragment object and return it.
createElement()Create an element node.
createElementNS()Creates an element node with the specified namespace.
createEntityReference(name)Create an EntityReference object and return it.
createProcessingInstruction(target,data)Create a ProcessingInstruction object and return it.
createTextNode()Create a text node.
getElementById(id)Returns the element with the ID attribute of the specified value. If no such element exists, null is returned.
getElementsByTagName()Returns the NodeList of all elements with the specified name.
getElementsByTagNameNS()Returns the NodeList of all elements with the specified name and namespace.
importNode(nodetoimport,deep)Select a node from another document to this document. This method creates a new copy of the source node. If the deep parameter is set to true, it will import all child nodes of the specified node. If set to false, it will only import the node itself. This method returns the imported node.
renameNode()Rename an element or attribute node.

3. Common document

  1. document.write('page output ');
  2. document.bgColor=‘#000’;// Add html by default
  3. document.documentElement;//html and all its contents
  4. document.head / / content pointing to head
  5. document.body / / content pointing to body
  6. document.body.style.color="#000" / / add color to the font in the body
  7. document.title / / points to the content of title
  8. document.URL / / get the complete URL of the current page
  9. document. Refer / / get the URL of the source page
  10. document. Domain / / refers to the domain name, which can be used to judge the domain name

7. document get node

  1. document.getElementById('element Id ')

  2. document.getElementByTagName('element node name ')

    When accessing, you can directly take the subscript or use item() to take the subscript. You can also use the method of namedItem() to access the attribute value of name

  3. document.getElementByClassName('element class')

  4. document.getElementByName('name ')

  5. document.querySekector("css selector"): find an element and return it

  6. document. Queryseketorall ("CSS selector"): find multiple elements and return the set composed of these elements (forEach can be used to traverse the set)

  7. Detect whether it is obtained by the above two methods: element Matchsselector ("CSS selector"), refers to anti true, no anti false

8. document special collection (pseudo array)

  1. document.anchors contains all the special effects with name in the document
  2. document. Collection of applets
  3. document. Collection of forms
  4. document. Collection of images
  5. document.links said there was a with a href

9. Writing of document

Four methods: write(), writeln(), open(), close()

  • writeln() is also a write string, but adds a newline (\ n) at the end

    When a script tag is nested inside a script tag, you can use this attribute to wrap it so that the tag can match the head and tail normally

  • The latter two methods use to open and close the browser's output stream

10. Node attribute style operation

attributes are no longer commonly used

  1. Add: element setAttribute("attribute name", "attribute value") [^ remark 7] ⭐

  2. Delete: element removeAttribute("attribute name" [, "attribute value"])

  3. Change: the attributes of the node are added and modified in an overlay manner

  4. Check: elements getAttribute("attribute name")

  5. Or directly add, delete, modify and query the attribute in the form of viewing object


Note: those with "-" and other special symbols can only use this form

  1. All of the above are to get and set inline styles. You cannot get css styles that are inline or external

    window. Getcomputestyle (element) css attribute name can get all css styles.

  2. Get node custom attributes: node dataset. Custom attributes; Available, settable

11. DOM operation technology

It is to dynamically generate a script tag, set the src attribute, or generate a link tag, set the href attribute, and then add the location corresponding to html

12. table method

  1. caption: holds the pointer to the element (if any)

  2. tBodies: indicates that there is a pointer to the element

  3. tFoot: holds the pointer to the element (if any)

  4. thead: holds the pointer to the element (if any)

  5. Rows: points to all rows

  6. Createheader(): creates an element, puts it into a table, and returns a reference

  7. createTFoot(): create elements, put them into the table, and return references

  8. createCaption(): creates an element, puts it into a table, and returns a reference

  9. Deletethread(): deletes an element

  10. deleteTFoot(): deletes an element

  11. deleteCaption(): deletes an element

  12. deleteRow(pos): deletes the row at the specified location

  13. Insert rows in the set

    Properties and methods added for

  14. Rows: point to rows

  15. deleteRow(pos): deletes the row at the specified location

  16. insertRow(pos): inserts a row at the specified position in the rows collection and returns a reference to the newly inserted row

    Properties and methods added for

  17. cells: point to td or th

  18. deleteCell(pos): deletes a cell at a specified location

  19. insertCell(pos): add a cell to the specified location of cells and return a reference to the newly inserted cell

13. Document related

  • document.hasFocus(); Determine whether the document gets focus
  • document.readyState(); Return to the document loading status: loading is loading and complete loading is completed
  • document.charset; Specifies the data type when the document is read

14. Insert tag (innerHTML) ⭐⭐

  • Node innerHTML='<p>hollo world</p>'; Can be obtained, can be set, and the label will be displayed after loading. There is a compatibility problem with the script tag
  • Node outerHTML; It's useless. The functions and are just to get special exchange, but it's also available on it
  • Node insertAdjacentHTML()
    • Insert: old node before element insertAdjaceHtml("beforebegin","<p>hollo world</p>")
    • Insert after element: old node insertAdjaceHtml("afterend","<p>hollo world</p>")
    • First child element insertion: parent node insertAdjacentHtml("afterbegin","<p>hollo world</p>")
    • The last element is inserted: parent node insertAdjacentHtml("beforeend","<p>hollo world</p>")

Using innerHTML to manipulate nodes reduces memory usage

15. Insert text

  • Node innerText; Only add content, not nodes
  • Node outerText;

16. Rolling

All elements can be used (Safari and Chrome implement this method)

  • scrollIntoViewIfNeeded([true]) the current container window is missing and visible after scrolling
  • scrollByLines(pos) sets the specified line height for element content scrolling
  • scrollByPages() sets the specified page height for element content scrolling

11. DOM2 and DOM3

Most of them are wordy and give up directly in teaching. Only the commonly used parts are listed

1. Element size

Read only attribute

  1. height: element offsetHeight
  2. width: element offsetWidth
  3. Positioned parent element: offsetParent (useless)
  4. left: element offsetLeft
  5. top: element offsetTop

2. Viewable window size

Without scroll bar

  1. height: element clientHeight
  2. width: element clientWidth
  3. left: element clientLeft
  4. top: element clientTop

3. Scroll size

  1. When there is no scroll bar, the total height of element content: element scrollHeight
  2. When there is no scroll bar, the total width of element content: element scrollWidth
  3. Distance from left when scrolling: element scrollLeft
  4. Distance from top when scrolling: element scrollTop

4. Determine element size

Element getBoundingClientRect(), which returns a rectangular object with four attributes: left, right, top and bottom. It's no use

5. Scope

Used to determine the scope of DOM, folding, special complex selection, etc.

12. Events

The interaction between JavaScript and HTML is realized through events.

1. Event flow

1. Event bubbling

The event of the child element will bubble up and trigger the same event of the parent element

2. Event capture

Getting the child element will be captured from the parent element layer by layer, and triggering the parent element will trigger the same event of the child element

3. DOM event flow

Event flow refers to the bubbling phase of events from the capture phase, and each event passes through the event flow

Of course, it can be stopped artificially, which will be described in detail later

2. Event handling

1. Event binding

Take a mouse click event as an example.

1. HTML inline binding
<input type="button" value="Button" onclick="fn">
<!--Click trigger fn Processing function-->
<!--You can bind only once. Binding again will overwrite the previous-->

2. on binding

This is to bind an uncalled processing function fn, which is triggered when input is clicked, and this of FN points to input instead of window global. Of course, it can still be changed through call, apply and bind.

let input=document.querySelector("input");
input.onclick=function fn(){
You can bind only once. Binding again will overwrite the previous

3. Add a listening event

The processing function is not called as above. The third parameter is whether to execute in the capture phase. The default is no and false
You can bind different handler functions multiple times. It can be a function name or an entire function, but it can't be called

input.addEventListener("click",Processing function,false);

2. Unbind event

1. Inline binding

Unbind directly with remove attribute


2. on unbinding

Set the handler function to null. Overwrite previous settings

3. Delete listening event

The parameters are the same as those in binding

input.removeEventListener("click",Processing function,false);

3. Compatible with IE8 and below

Bind as: attachEvent()

Unbind as: detectevent()

IE8 only supports bubbling. Its usage is the same as monitoring events.

4. Cross browser event handling

This thing has hardly been mentioned. Find out

The addHandler() binding method receives three parameters: the element to be operated, the event name and the event handler function

The corresponding object is removeHandler(). To use EventUtil, please query it online

3. Event object E

Every event triggered on the DOM will generate an event object, which contains all the information related to the event

1. Description of e

Properties / methodstypeRead / writeexplain
bubblesBooleanread-onlyIndicates whether the event is bubbling
cancelableBooleanread-onlyIndicates whether the default behavior of the event can be canceled
currentTargetElementread-onlyThe element whose event handler handles the event properly
defaultPreventedBooleanread-onlytrue indicates that preventDefault() has been called
detailIntegerread-onlyDetails related to the event
eventPhaseIntegerread-onlyCall the stage of the event handler, 1 capture, 2 with the target, 3 bubbling
prevent Default()Functionread-onlyCancels the default behavior of the event. If cancelable is true, it can be used
stopImmediatePropagation()Functionread-onlyCancels further capture or bubbling of events while preventing any events from being called
stopPropagation()Functonread-onlyCancel further capture or bubbling of events. If bubbles is true, you can use
targetElementread-onlyTarget of the event
trustedBooleanread-onlyGenerated for true table browser and false for developer JavaScript
typeStringread-onlyType of event triggered
viewAbstractViewread-onlyThe abstract diagram associated with the event is equivalent to the window in which the event occurs

2. Get event object

  1. window.event
  2. var er=e || window.event [^ note 8] (short circuit operation is used here)
  3. box.onclick=function(e){console.log(e)}

3. Common use of e

  1. Get mouse button information use: e.button: (detailed introduction to mouse events)
  2. e.type: used to obtain the event type. For example, click is the click event and blur is the lost focus.
  3. e.keyCode to obtain the key ascll code of pressing the keyboard key
  4. e.target gets the event target (the precise target element of the event) ⭐
  5. e.stopPropagation() prevents event bubbling ⭐
  6. e.preventDefault() prevents the default behavior of the event ⭐ Or append return false at the end of the event handler function, or set javascript: for the link address& javaScript:voidlo)

4. e compatibility

  1. e. Srclelement obtains the event target (the precise target element of the event) (Firefox browser also obtains it through srclelement)
  2. e.cancelBubble prevents the event from bubbling
  3. e.returnValue block event default behavior

5. e get cursor position

  1. x axis: e.offsetX; y axis: e.offsetY; [^ note 9]
  2. x axis: e.clientX; y axis: e.clientY; [^ note 10]
  3. x axis: e.pageX; y-axis: e.pageY; [^ note 11]

6. Event Hosting Technology

Event delegation is also called event agent (from whose perspective). Using event delegation technology can avoid adding event listening to each child node. On the contrary, event listening can be delegated to the parent element, which can improve the performance of binding events

oUl.onclick = function(e){
	var ev = e || window.event;
	// Gets the dom object of the clicked target element
	var target = ev.target || ev.srcElement;
	// Determine whether it is a li tag
	if(target.nodeName == "LI"){
        //⭐⭐⭐ Note that the browser has been changed to uppercase
        //It is not necessary to verify nodeName
		// Complete business logic

4. Event type

1. Ul event (window)

  1. window.onload=fn; Last load event

  2. window.onunload=fn; Close browser trigger event

  3. window.onbeforUnload=fn; Event triggered immediately before closing the browser

  4. abort: when the user stops the download process, if the embedded content is not loaded, it will be triggered on the element

  5. Error: triggered on the window when JavaScript error occurs, on the element when the image cannot be loaded, and on the element when the content cannot be loaded

  6. window.onselect=fn;: Triggered when the user selects a text box

  7. window.onresize=fn;: Triggered on the window or frame when the size of the window or frame changes

  8. scroll;: Scroll bar scrolling event, triggered by the element that scrolls

  9. Implementation of browser window switching detection ⭐: https://www.cnblogs.com/xulinjun/p/11452001.html

    visibilitychange property

    document.addEventListener('visibilitychange',function(){ //Browser switching event
        if(document.visibilityState=='hidden') { //State judgment
            document.title = 'Title II'; 
        }else {
            document.title = 'Title I';

2. Information acquisition of scroll event

  1. Scroll up and down: document documentElement. scrollTop
  2. Scroll up and down: document body. scrollTop
  3. The above two require short circuit writing to prevent compatibility problems
  4. Left and right is to change top to left

3. Focus event

  1. blur: triggered when the element loses focus. There is no bubble and no compatibility problem
  2. Focus: triggered when the element obtains the focus. There is no bubble and no compatibility problem
  3. Focus in: triggered when the element gets focus, bubbling, IE5 5+,Safari5. 1+,Opera11. 5 +, supported by chrome
  4. Ditto: when the element is triggered, focus is lost

4. Mouse event

  1. Left click: Click
  2. Right click: contextmenu
  3. Double click: dblclick
  4. Left click: mousedown
  5. Left click: mouseup
  6. Mouse up [^ note 12]: mouseover
  7. Mouse away [^ note 12]: mouseout
  8. ⭐ (excluding children) mouse up [^ note 13]: mouseenter
  9. ⭐ (excluding children) mouse away [^ remark 13]: mouseleave
  10. Mouse movement event: mousemove

5. Cursor position

Object get event

6. Modify key

Modify mouse events through shift, ctrl, alt, window or cmd. Since users can hardly use shortcut keys and key combinations, they will not be introduced


Mouse button judgment

  1. Return 0: indicates that the mouse button is not pressed
  2. Returning to 1: means pressing the left key
  3. Returning to 2 means pressing the right key
  4. Return to 3: press the left and right keys at the same time
  5. Return to 4: press the pulley key
  6. Return to 5: press the left + pulley key
  7. Return to 6: press the right + pulley key
  8. Returning to 8 means pressing three keys

8. Mouse wheel event

ie6 first implements: mousewhere event. The corresponding event object contains a special attribute, wheldelta. When sliding up, it is a multiple of 120 and when sliding down, it is a multiple of - 120

Opera9. It was the opposite before version 5

9. Keyboard events

  1. Press: keydown

  2. Pop up: keyup

  3. Pop up no matter you press: keypress

  4. Judgment key code: obtain judgment through e.keyCode

  5. Judgment key combination:

    1. Press the alt key to get true, otherwise get false: altKey
    2. Press the shift key to get true, otherwise get false: shiftKey
    3. Press ctrl to get true, otherwise get false: ctrl key
  6. In the editable area, enter: textInput: new for DOM3

    The input method can be determined through the special attribute inputMethod of its event object

    • 0: indicates that the browser is not sure how to enter
    • 1: Keyboard input
    • 2: Paste
    • 3: Put into
    • 4: Use IME input
    • 5: Form input
    • 6: Handwriting input
    • 7: Language input
    • 8: Combined input of the above methods
    • 9: Script input

10. Form event

  1. Submit form: submit
  2. Get focus: focus
  3. Lose focus: blur
  4. Content changes and loses focus: change
  5. The value of input changes in real time: input
  6. input event in lower version IE: onpropertychange
  7. Prevent submitting events use the block default event: e.preventDefault()
  8. checkbox judgment: input ckecked||input. checked=true.

11. Encapsulation of events

function bind(ele,type,callback){

  1. Binding is bind
  2. Others are unbind
  3. Object to bind event: ele
  4. Event type: type
  5. Callback function for handling events: callback

11. Symbol:

There are also some relatively unpopular events: composite events, change events and HTML5 events. These events are designed and detected for developers and will not be introduced.

12. Device events 🌙

I really can't do this. Due to the continuous release and use of comprehensive screen, great changes are taking place in keys and methods. There are specific modules on jQuery Mobile, so it's impossible to carry out mobile device experiments

13. Form supplement

Most of them have been introduced in html, and only some properties and methods of js are introduced

1. Operating the pasteboard

Opera does not support accessing the pasteboard through JavaScript

  • berorecopy: triggered before a complex operation occurs
  • copy: triggered when a complex operation occurs
  • Before cut: triggered before the cutting operation occurs
  • Cut: triggered when a cut operation occurs
  • Before paste: triggered before the paste operation occurs
  • Paste: triggered when a paste operation occurs

2. Auto switch focus

Active focus: focus()

Judge the word number of input, and add input when the conditions are met Focus() causes the input element that should be obtained to obtain the focus

3. Rich text editing 🌙

iframe tag content compilation

1. Using the contenteditable attribute

You can assign the contenteditable attribute to any element in the page, and then you can edit the element

<div class="editable" id="richedit" contenteditable></div>

You can also turn compilation mode on and off

div.contenteditable=true;//true: open; false: close; Inherit: inherit the parent element

2. Action rich text

document.execCommand() is extremely popular and may not be used for a lifetime. Continue editing later

3. Rich text selection

Use the getSelection() method of the framework (iframe); Continue editing later

14. Canvas drawing 🌙

Most anticipated features

15. Offline application storage problem

1. Offline detection

navigator.onLine; Judge whether the network is connected. Yes, no, false. It was mentioned earlier when introducing navigator

Available. Modifiable assignment

2. Application cache

HTML5's application cache, or appcache for short, means that web applications can be cached and accessed without an Internet connection.

Application caching brings three advantages to applications:

  1. Offline browsing - users can use them when applications are offline
  2. Speed - cached resources load faster
  3. Reduce server load - the browser will only download updated or changed resources from the server.

Detect that the status of the application cache is applicationcache Status, the attribute value is a constant

  • 0: no cache
  • 1: Idle
  • 2: Checking: download the description file and check for updates
  • 3: Downloading
  • 4: Update completed: it has been downloaded and can be used through swapCache()

There are many related events in the application cache, indicating the change of its state

  • checking: triggered when the browser finds updates for the application cache
  • Error: an error occurred while looking for updates or downloads
  • noupdate: triggered when checking the description file and finding that the file has not changed
  • Downloading: triggered when downloading application resources
  • progress: it is triggered continuously during the process of file downloading and application caching
  • updateready: after the new application is downloaded on the page, it can be triggered through swapCache()
  • cached: triggered when the application cache is fully available


1. Request header information

HTTP cookies are usually called cookies directly

When a set cookie occurs, the request header is as follows:

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie:name=value;expires=Mon, 22-Jan-20 07:10:24 GMT;domain=.wrox.com
//URL encoding is required for all transfers

Send the information back to the server every time the Cookie HTTP header is added

GET /index.html HTTP/1.1
Cookie: name=value

2. Number limit

The minimum number of cookie s for low version IE is 20, and the best number for others is no more than 50

The last word count is within 4095B

3. Add, delete, modify and check

1. Add / modify: document Cookie = "key = value [, expiration time]"

If the expiration time is not set, it will expire when the browser is closed by default, and the expiration time is the international coordination time. For China, 8 hours will be subtracted, and the unit is milliseconds

2. Delete: document Cookie = "key = null, one second before the current time"

Cookies cannot be deleted directly and manually. They can only be deleted in advance.

3. Check: document cookie(); Get all cookies and return a string

4. Encapsulated simple cookie function (this is simple and crude, but not the best)

/*jshint esversion: 6 */
//Functions that set or add or modify cookie s
(function (){
    return function setCookie(key,value,indite){
        let date=new Date();
//Read specified cookie encapsulation
(function (){
    return function getCookie(key){
        const cookieArr=document.cookie.split(";");
        let value="";
        return value;
//Delete cookie encapsulation
(function (){
    return function delCookie(name){

The concept of sub cookie is to store smaller segments of cookies in cookies


Due to various compatibility and bug problems of other methods, all of them are not introduced. With their strong development, they will be supplemented

1. Local storage

  1. The 4k limit of cookie s is lifted, and the storage capacity can reach 5m

  2. After accessing the server for the first time, you can send data and store it in the client's browser

  3. The lower version of the browser does not support ie8

  4. Protected by the same origin policy.

  5. Version support detection

        alert("Please upgrade your browser");
    //Business logic code

2. Add, delete, modify and check

  1. Add / modify

    //Check in localSrotage, and it is also used for overlay creation, that is, modification
  2. obtain

    let str=localStorage.getItem('name');
    let str=localStorage.key(subscript);//Get the value of the specified subscript key, which is not recommended because you also know the specific subscript
  3. delete

    localStorage.clear();//Empty all local storage.

3. And json

let obj={
    name:'Sister pomegranate',
let str=JSON.stringify(obj);
localStorage.setItem('info',str);//Save the converted data to local storage
let read=localStorage.getItem('info');
console.log(JSON.pares(read));//Read as transfer object

4. storage event

Used to listen for locally stored events

  • Domain: the domain name of the changed storage space
  • Key: set or delete the key name
  • newValue: if it is a set value, it is a new value; null if delete key
  • oldValue: the value before the key is changed

5. indexedDB database 🌙

Follow up processing

16. AJAX and Comet 🌙

-----------------Relevant contents can be obtained by jumping to the home page


17. Some functions are better than vscode plug-ins


It's not easy to summarize. I think this blog is helpful for you and recommend collection. Thank you for your attention and praise. Your support for me is the greatest encouragement to continue writing~

Topics: Javascript