current position:Home>Basic summary of JavaScript advanced

Basic summary of JavaScript advanced

2022-04-29 08:09:13Chen Chen is trying

One 、JavaScript Basic summary

1、 Knowledge points related to data types

Ⅰ- basic ( value ) type

  1. String: Any string
  2. Number: Any number
  3. boolean: true/false
  4. undefined: undefined
  5. null: null --> Use typeof When to return to object
  6. symbol (ECMAScript 2016 newly added ). -->Symbol yes Basic data type A kind of ,Symbol The object is Symbol Of the original value encapsulation (en-US) .
  7. bigint, -->BigInt It's a digital type of data , It can represent integers in any precision format .

Add the bottom [ object ] type , at present javaScript There are eight data types

Ⅱ- object ( quote ) type

  1. Object: Any object
  2. Function: A special object ( It can be executed ) -- It contains runnable code
  3. Array: A special object (key Subscript attribute for numeric value , The internal data is ordered )

Ⅲ- Judgment method

①* typeof*

typeof The operator returns a character string , Represents the type of uncomputed operand .

  • Can be judged : undefined/ The number / character string / Boolean value / function

  • Can't judge : null And object object And array

  • Be careful : function console.log(typeof undefined) when , What you get is also a character string , Also lowercase !!–> 'undefined'

  • Code example

 // typeof Returns a string representation of a data type 
 var a

 // Be careful :typeof The returned string is 
 console.log(a, typeof a, typeof a==='undefined',a===undefined )  // undefined 'undefined' true true
 console.log(undefined === 'undefined') //false
 a = 4
 console.log(typeof a==='number') //true
 a = 'hongjilin'
 console.log(typeof a==='string') //true
 console.log(typeof a==='String') //false --> Be careful , The returned type is lowercase 
 a = true
 console.log(typeof a==='boolean') //true
 a = null
 console.log(typeof a, a===null) // 'object' true
let b={
     }
 console.log(typeof b,typeof null, '-------') // 'object' 'object' --> therefore Typeof Can't judge null And object

②*instanceof*( How to judge the instance )

  • Specifically judge the object Specific types of

  • instanceof Operator For detecting constructors prototype Whether the attribute appears in the prototype chain of an instance object .

  • Code example :

 var b1 = {
     
   b2: [1, 'abc', console.log],
// Can be reduced to  b3:()=>()=> 'hongjilin' --> Knowledge of higher-order functions 
   b3: function () {
     
     return  () =>{
       return   'hongjilin'}
   }
 }
/** Use instanceof Make object judgment */
 console.log(b1 instanceof Object, b1 instanceof Array) // true false
 console.log(b1.b2 instanceof Array, b1.b2 instanceof Object) // true true
 console.log(b1.b3 instanceof Function, b1.b3 instanceof Object) // true true

 /** Use typeof Judge an attribute in an object */
console.log(typeof b1.b2, typeof null) // 'object' 'object' 
 console.log(typeof b1.b3==='function') // true
 console.log(typeof b1.b2[2]==='function') //true

 /** Call an object and an example of a function in the array */
 b1.b2[2](' call console.log Print hongjilin')    // call console.log Print hongjilin
 console.log(b1.b3()()) // hongjilin

③*===*

For details, see MDN Of JavaScript The equality judgment in

Can be judged : undefined, null

In short , When comparing two things , The double equal sign performs type conversion ; The three equal signs will make the same comparison , Without type conversion ( If the type is different , Just always return false )

Ⅳ- Related problems

undefined And null The difference between ?

  • undefined Represents that the definition is not assigned

  • nulll Defines and assigns , It's just worth it null

  • Code example

var a
console.log(a)  // undefined
a = null
console.log(a) // null

When to assign a variable to null Well ?

  • The initial assignment , Indicates that the object to be assigned is , It can be used as a conventional placeholder

  • Before the end of the , Make objects garbage objects ( Recycled by a garbage collector )

  • Code example

// start , It can be used as a conventional placeholder 
var b = null  //  The initial assignment is null,  Indicates that the object to be assigned is 
// Assign a value when the object is determined 
b = ['atguigu', 12]
// Finally, when not in use , Leave its reference blank , You can release b The memory occupied by this object  --- When there is no reference to the object pointing to it, it is called a garbage object 
b = null //  Give Way b The object pointed to becomes a garbage object ( Recycled by a garbage collector )

Strictly distinguish between variable type and data type ?

  • Type of data
  • Basic types
  • object type
  • The type of variable ( The type of variable memory value )
  • Basic types : Preservation is Basic types The data of
  • Reference type : Save the address value ( object type )

Ⅴ- Supplementary information :

① String comparison *>< as well as charCodeAt()* Method

  1. Javascript The string is greater than ( Less than ) When comparing , According to the first different character ascii Value code for comparison , When the number (number) And string (string) When the comparison is large , Will force the number (number) Convert to string (string) Then compare
(function(){
     
  console.log('13'>'3'); //  Output :false
  console.log(5>'6');  //  Output : false
  console.log('d'>'ABDC') //  Output : true
  console.log(19>'ssf') //  Output  false
  console.log('A'>'abcdef') //  Output  false
})()
  1. Manually switch to ascii Post subtraction , Use positive and negative numbers to express the size
sorter={(a:string,b:string)=> a.charCodeAt()-b.charCodeAt()}

2、 data , Variable , Memory understanding

Ⅰ- What is data ?

  1. Stored in memory to represent specific information ’ thing ’, Essentially, 0101…
  2. Characteristics of data : Transitive , Computable -->let a=0;b=a Reflect transitive
  3. Everything is data
  4. The target of all operations in memory : data
  • Arithmetic operations

  • Logical operations

  • assignment

  • Operation function

Ⅱ- What is memory ?

  1. The space that can store data after the memory module is powered on ( temporary )

  2. Memory generation and death : Memory module ( Circuit board )> Electrify > Generate memory space ==> Store the data ==> Processing data ==> power failure ==> Memory space and data disappear

  3. A small memory 2 Data

  • Data stored internally

  • Address values

  1. Memory classification
  • Stack : Global variables / local variable

  • Pile up : object

Ⅲ- What is a variable ?

  • Variable quantity , It consists of variable name and variable value
  • Each variable corresponds to a small piece of memory , The variable name is used to find the corresponding memory , Variable values are data stored in memory

ps: Variable obj.xx–>. It is equivalent to holding the address to find the corresponding memory in the back , So only if I have an address in my variable , Just can use .

Ⅳ- Memory , data , The relationship among variables

  • Memory is the space used to store data
  • Variable is the identifier of memory

Ⅴ- Related problems

About assignment and memory

let a = xxx, a What is stored in memory ?

  • xxx It's basic data , This is the data
  • xxx It's the object , Save the address value of the object
  • xxx It's a variable , The saved xxx Memory content of ( Maybe basic data , It could also be the address value )

On the assignment of reference variables

  • 2 Two reference variables point to the same object , Modify the internal data of the object through a variable , Another variable sees the modified data

  • 2 Two reference variables point to the same object , Let one of the reference variables point to another object , Another reference variable still points to the previous object

  • Code example :

let a = {
     age: 12}
// At this time, the a The address value pointed to is assigned to B, therefore B This also points to {age:12} This memory 
let b = a
// At this point, a memory is recreated and a Pointing to it , So here a Pointing to {name:'hong'}, and b The point is still the initial point {age:12}
a = {
     name: 'hong'}
// here a And b The memory pointed to is different , So the changes don't affect each other 
b.age = 14
console.log(b.age, a.name, a.age) // 14 hong undefined
//2 Two reference variables point to the same object ,  Let one of the reference variables point to another object ,  Another reference variable still points to the previous object  --> therefore  a  Is still  {name: 'hong'}
const fn2=(obj) => obj = {
     age: 15}
fn2(a)
console.log(a.age) //undefined 

stay js When a function is called and a variable parameter is passed , Value passing or reference passing

  • understand 1: It's all worth it ( basic / Address values ) Pass on

  • So actually upload into function The parameter in is also to find the memory with its stored address value

// incoming obj What's stored is a Address value stored in , therefore obj==a( Because they have the same address value , Point to the same )
//2 Two reference variables point to the same object ,  Modify the internal data of the object through a variable ,  Another variable sees the modified data  --> So it was modified 
 let a = {
     name: 'hong'}
 const fn2=(obj) => obj.age= 15
 fn2(a)
 console.log(a.age) //15
  • understand 2: It could be value passing , It could also be reference passing ( Address values )

JS How the engine manages memory ?

  1. Memory life cycle
  • Allocate small memory space , Get the right to use it

  • Store the data , You can do it over and over again

  • Free up small memory space

  1. Free memory
  • local variable : Automatically release after function execution

  • object : Become a garbage object ==> Garbage collector recycling

var a = 3
var obj = {
     name:"hong"}
obj = undefined ||null  // here ,obj Not released , But as previously stated `{name:"hong"}` Because no one points to it , You will be recycled by the garbage collector at a later time 

function fn () {
      var b = {
     }}
fn() // b It's automatic release , b The object pointed to is collected by the garbage collector at a later time 

3、 object

Ⅰ- The concept of object

What is an object ?

  • Multiple data packages
  • A container used to hold multiple data
  • An object represents a thing in reality

Why use objects ?

  • Unified management of multiple data

The composition of the object

  • attribute : Property name ( character string ) And property values ( arbitrarily ) form
  • Method : A special property ( Property values are functions )

Ⅱ- How to access the internal data of the object ?

  • . Property name : The coding is simple , Sometimes it doesn't work
  • [' Property name ']: Coding trouble , Can be universal

Ⅲ- When must I use [' Property name '] The way ?

  1. Property names contain special characters : - Space
  2. The property name is uncertain
var p = {
     }
//1.  to p Object to add a property : content type: text/json
// p.content-type = 'text/json' // Out-of-service 
p['content-type'] = 'text/json'
console.log(p['content-type'])

//2.  The property name is uncertain 
var propName = 'myAge'
var value = 18
// p.propName = value // Out-of-service 
p[propName] = value
console.log(p[propName])

4、 function

Ⅰ- The concept of function

What is a function

  • To achieve a specific function n The encapsulation of a statement
  • Only functions can be executed , Other types of data cannot be executed

Why use functions ?

  • Improve code reuse
  • Easy to read and communicate

How to define a function ?

  • Function declaration

  • expression

function fn1 () {
      // Function declaration 
  console.log('fn1()')
}
var fn2 = function () {
      // expression 
  console.log('fn2()')
}

Ⅱ- How to call ( perform ) function

  1. test(): Call directly

  2. obj.test(): Call... By object

  3. new test(): new call

  4. test.call/apply(obj): Temporarily let test Become obj Method to call

> * [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-yBWIrieV-1650369482428)(.\JavaScript senior .assets\image-20210705185535337.png)]

  1. Code example
  var obj = {
     }
  // The arrow function... Cannot be used here , Because the arrow function changes this Point to 
  function test2 () {
     
    this.xxx = 'hongjilin'
  }
  // obj.test2()  Not directly ,  There is no such thing as 
  test2.call(obj)  //  You can call a function as a method of specifying any object 
  console.log(obj.xxx)

Ⅲ- Callback function

What function is a callback function ?

  • You define
  • You didn't tune
  • But in the end it did ( At a certain time or under certain conditions )

Common callback functions ?

  • dom Event callback function ==> What happened dom Elements
  • Timer callback function ===>window
  • ajax Request callback function ( Later on )
  • Life cycle callback function ( Later on )
document.getElementById('btn').onclick = function () {
      // dom Event callback function 
  alert(this.innerHTML)
}
setTimeout(function () {
      //  Timer callback function 

  alert(' It's time '+this)
}, 2000)

Ⅳ-IIFE ( Self calling function )

  1. Full name : Immediately-Invoked Function Expression Self calling function

  2. effect :

  • Hide the implementation

  • Will not pollute the outside ( Generally refers to the overall situation ) Namespace

  • Use it to encode js modular

  1. Code example
  (function () {
      // Anonymous function self call 
      var a = 3
      console.log(a + 3)
  })()
  console.log(a) // a is not defined

  // Why is there a `;`--> Because there is a... Outside the calling function () The parcel , With the possibility of () Together, the code at the end is considered a function call 
  // Not adding a semicolon may be considered like this  console.log(a)(IIFE)
  ;(function () {
     // Will not pollute the outside ( overall situation ) Namespace --> give an example 
      var a = 1;

      function test() {
     
          console.log(++a)
      } // Declare a local function test
      window.$ = function () {
     
          return {
     
              test: test
          }
      }//  Expose a global function 
  })()
  test()  //test is not defined
  $().test() // 1. $ It's a function  2. $ An object is returned after execution 

Ⅴ- Function this

this What is it? ?

  • Any function is essentially called through an object , If there is no direct designation, it is window
  • All functions have a variable inside this
  • Its value is The current object of the calling function

How to determine the this Value ?

  • test(): window
  • p.test(): p
  • new test(): Newly created objects
  • p.call(obj): obj

Detailed code examples

function Person(color) {
     
  console.log(this)
  this.color = color;
  this.getColor = function () {
     
      console.log(this)
      return this.color;
  };
  this.setColor = function (color) {
     
      console.log(this)
      this.color = color;
  };
}

Person("red"); //this Who is it? ? window

const p = new Person("yello"); //this Who is it? ? p

p.getColor(); //this Who is it? ? p

const obj = {
     };
// call call Will change this Point to --> Let me p The function becomes `obj` Call the temporary method of 
p.setColor.call(obj, "black"); //this Who is it? ? obj

const test = p.setColor;
test(); //this Who is it? ? window --> Because it directly calls 

function fun1() {
     
  function fun2() {
     
      console.log(this);
  }

  fun2(); //this Who is it? ? window
}

fun1();// call fun1

5、 About statement semicolons

  1. js A statement can be followed without a semicolon
  2. Whether to add a semicolon is a matter of coding style , No, should not , Only you like it or not
  3. Hereunder 2 In this case, there will be a problem without a semicolon
  • The previous statement that begins with parentheses
  • The previous sentence beginning with square brackets
  1. terms of settlement : Add a semicolon at the beginning of the line
  2. A powerful example of : vue.js library
  3. It's a hot topic : https://www.zhihu.com/question/20298345
	var a = 3
    ;(function () {
    

    })()
    /*  Wrong understanding  var a = 3(function () { })(); */

    var b = 4
    ;[1, 3].forEach(function () {
    

    })
    /*  Wrong understanding  var b = 4[3].forEach(function () { }) */

copyright notice
author[Chen Chen is trying],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290809096535.html

Random recommended