ES5 and ES6 NEW

Posted by daniel_lee_hill on Sat, 25 Dec 2021 06:10:00 +0100

catalogue

1. ES6 - define variables

2. ES6 - template string

3. ES6 - arrow function

4. ES6 - function parameter default value

5. ES6 - deconstruction assignment

Interview case:

6. ES6 - extension operator

7. ES6 - object abbreviation syntax

8. ES6 - Modular Development

9. ES6 - class syntax

10. Legend:

+ECMAScript is a version in the development process
=>Official: ES2015
=>Community: ES6
+ES6 and all the contents after ES6 are incompatible with the lower versions of IE

1. ES6 - define variables

ES2015(ES6) adds two important JavaScript Keywords: let , and , const.

The variables declared by let are only valid in the code block where the let command is located,

const declares a read-only constant. Once declared, the value of the constant cannot be changed.

1. let: variable
2. const: constant

  1. The difference between let / const and var
    1-1. Pre analysis
= > in the process of pre parsing, the variables defined by var will be pre parsed. You can use them first and then define them
= > let / const does not perform pre parsing and must be defined before use

// 1-1.  Pre analysis
console.log(num)		// undefined
var num = 100
console.log(num)		// 100
// let defines variables without pre parsing
console.log(num)	// Will report an error
let num = 100
console.log(num)
// const defines variables without pre parsing
console.log(num)	// Will report an error
const num = 100
console.log(num)


    1-2. Duplicate declaration (variable name)
Using var can define as like as two peas of two variables, but the second definition is meaningless, and assignment is meaningful.
= > let / const is not allowed to define variables with duplicate names under the same scope

// 1-2.  Repeat declaration
var n = 100
var n = 200
console.log(n)	// 200
let n2 = 200
let n2 = 300	// Error = > identifier 'N2' has already been declared

const n3 = 300
const n3 = 400	// Error = > identifier 'N3' has already been declared


    1-3. Block level scope
= > VAR has no block level scope
= > let / const has block level scope
= > block level scope: any {} that can write code segments will limit the use range of variables

// 1-3.  Block level scope
if (true) {
  var num = 100
  console.log(num)	// 100
}
console.log(num)	// 100
if (true) {
  let num = 100
  console.log(num)	// 100
}
console.log(num)	// Error = > num is not defined

if (true) {
  const num = 200
  console.log(num)
}
console.log(num)		// Error = > num is not defined


  2. The difference between let and const
    2-1. Assignment on declaration
= > let can not assign values when defining variables
= > const must be assigned when defining variables

// 2-1.  Assignment problem
let num
console.log(num)	// undefined
num = 200
console.log(num)	// 200
// An error will be reported. You must assign a value during initialization. You cannot define a constant without assigning a value
const n // Error = > missing initializer in const declaration


    2-2. Modification of values
= > the values of the variables defined by let can be modified arbitrarily
= > the value defined by const is assigned during definition. Once assigned, it cannot be modified

// 2-2.  Modification of values
let n = 100
console.log(n)		// 100
n = 'hello world'
console.log(n)		// hello world

const str = 'I wrote it when I defined it'
console.log(str)	// I wrote it when I defined it
// When you try to modify a const defined constant
// An error will be reported directly because constants declared by const cannot be modified
str = 'hello world'

  

The for loop counter is very suitable for let

for (var i = 0; i < 10; i++) {
  setTimeout(function(){
    console.log(i);
  })
}
// Output ten 10
for (let j = 0; j < 10; j++) {
  setTimeout(function(){
    console.log(j);
  })
}
// Output 0123456789

The variable i is declared with var and is valid in the global range, so there is only one variable i in the global. In each cycle, i in the setTimeout timer refers to the global variable i, and the ten settimeouts in the cycle are executed after the end of the cycle, so i at this time is 10.

The variable J is declared with let. The current j is only valid in this cycle. J in each cycle is actually a new variable, so J in the setTimeout timer is actually a different variable, that is, 0123456789 is finally output. (if the variable J of each loop is redeclared, how do you know the value of the previous loop? This is because the JavaScript engine will remember the value of the previous loop.)

Key points:

How does const prevent variables from changing after declaration initialization? In fact, const does not guarantee that the value of the variable remains unchanged, but that the data stored at the memory address pointed to by the variable cannot be changed. At this point, you may have thought that simple data types and complex data types save values differently. yes, For simple data types (numeric number, string, boolean), the value is stored at the memory address pointed to by the variable, so the simple data type variable declared by const is equivalent to a constant, while the complex data type (Object, Array, Function). The memory address pointed to by the variable actually stores a pointer to the actual data, so const can only ensure that the pointer is fixed. As for the data structure pointed to by the pointer, it cannot be controlled. Therefore, be careful when using const to declare complex data type objects.

2. ES6 - template string

+ES6 adds a new way to define strings = > template strings
The template string is an enhanced version of the string
+Use backquotes (` `) to define strings
+It is no different from the string defined by single quotation mark (') or double quotation mark (""), and the use is the same
+Only when you use backquotes (` `) to define, you have special abilities
Characteristics of template string:
  1. You can write strings on new lines
  2. You can splice and parse variables directly in the string
= > when you need to parse variables, write ${variables}
+Note:
= > ${} the space outside is the real space inside the string
= > ${} is a space in the code and has nothing to do with the string

const s1 = 'hello world'
const s2 = "hello world"
const s3 = `hello world`
console.log(s1, typeof s1, s1.length, s1.slice(0, 5))
console.log(s2, typeof s2, s2.length, s2.slice(0, 5))
console.log(s3, typeof s3, s3.length, s3.slice(0, 5))
console.log(s1 === s2)		// true

// Feature 1: line feed writing string
let str = `
  hello world
  Hello world
`
console.log(str)
// Feature 2: parsing variables
let age = 18
let arr = [ 100, 200, 300 ]
// Normal single quotation mark (')
let s1 = 'Hello, I'm this year ${ age } Years old'
// ${} can write a simple expression
let s2 = `Hello, I'm this year ${ arr.length ? arr[arr.length - 1] : 18 } Years old`
console.log(s1)
console.log(s2)

 

3. ES6 - arrow function

Arrow functions provide a more concise way to write functions.
+A way to define functions in ES6 syntax
+Can only be used to define function expressions (assignment function / anonymous function)
= > when you assign a function as a value to another content, it is called a function expression
  => var xxx = function () {}
  => var obj = { xxx: function () {} }
  => xxx.onclick = function () {}
  => xxx.addEventListener('click', function () {})
  => xxx.forEach(function () {})
  => setTimeout(function () {}, 1000)
  => setInterval(function () {}, 1000)
  => ...
+Note: declarative functions do not work
  => function fn( ) { }
+Syntax of arrow function: () = > {}
- > () write the position of the function parameter
- > = > is the flag of the arrow function
The function body of the - > {} function is the location where the code segment is written

// Write an arrow function
const fn = function () { console.log('I'm a function') }
const fun = () => { console.log('I am also a function') }
fn()
fun()

Difference between arrow function and function expression
1. There are no arguments in the arrow function
= > a pseudo array in the function, which is a collection of all arguments
2. There is no this in the arrow function
= > official: this in the arrow function is this in the context
= > private: who is this outside the arrow function and who is this inside the arrow function
Characteristics of arrow function: (not mandatory)
1. Parentheses can be omitted
= > when you have only one formal parameter, you can not write parentheses
= > if you have no or two or more formal parameters, you must write parentheses

// 1. Omit parentheses
//No formal parameters, parentheses must be written
let fn1 = () => { console.log('I am fn1 function, I have no formal parameters') }
fn1()
// A formal parameter, you can not write parentheses
let fn2 = a => { console.log('I am fn2 function, There is one parameter', a) }
fn2(10)
// Two formal parameters must be written in parentheses
let fn3 = (a, b) => { console.log('I am fn3 function, There are two parameters', a, b) }
fn3(100, 200)

2. Braces can be omitted
When your code has only one sentence, you can omit braces and return the result of this sentence automatically
Otherwise, braces must be written

// 2. Omit braces
// This is an arrow function. There is only one sentence of code in the function, which is a + b
// The return value of this function is the result of a + b
let fn1 = (a, b) => a + b
let res = fn1(10, 20)
console.log(res)	// Print = > 30
// Abbreviated process
const arr = [ 1, 2, 3, 4, 5, 6, 7 ]
// var res = arr.filter(function (item) { return item % 2 })
// var res = arr.filter((item) => { return item % 2 })
// var res = arr.filter(item => { return item % 2 })
const res = arr.filter(item => item % 2)
console.log(res)    // Print = > (4) [1, 3, 5, 7]

3. There are no arguments in the arrow function
= > the arrow function does not contain arguments
= > a collection without all arguments

// 3. No arguments
const fn1 = function () { console.log(arguments) }
fn1(10, 20, 30)
const fn2 = () => { console.log(arguments) }
fn2(10, 20, 30)


4. There is no this in the arrow function
= > official: this of external scope
= > private: who is the function this written outside the arrow function and who is this in the arrow function
Note: it cannot be used as a constructor, that is, the new command cannot be used, otherwise an error will be reported

 

// 4. There is no this in the arrow function
const obj = {
  name: 'I am obj object',
  f: function () {
	console.log('f : ', this)
  },
  f2: () => {
	// There is no this here. The external this is used
	console.log('f2 : ', this)
  }
}
obj.f()
// According to the calling method, this in f2 should be obj
// Because f2 is an arrow function, there is no this in this function
// This uses the context of this
obj.f2()

4. ES6 - function parameter default value

+Set a default value for the formal parameter of the function. When you do not pass an argument, use
+Writing: when writing a formal parameter directly, assign a value to the formal parameter with the assignment symbol (=) and set the default value
+Any function can be used
+The arrow function can also set parameter default values:
=>Note: if you set the parameter default value for the arrow function, no matter how many formal parameters
=>You need to write parentheses

// The default value of parameter a is set to 10
// The default value of 20 is set for parameter b
function fn(a = 10, b = 20) {
  console.log('fn Printing within functions')
  console.log('a : ', a)
  console.log('b : ', b)
  console.log('---------------------')
}
// The arrow function can also set default values
const fn = (a = 10, b = 20) => {
  console.log('fn Printing within functions')
  console.log('a : ', a)
  console.log('b : ', b)
  console.log('---------------------')
}
// First call
// If you assign values to two formal parameters, the default values will not be used
fn(100, 200)
// Second call
// If b is not assigned a value, b will use the default value of 20
fn(1000)
// Third call
// Both a and b have no arguments for assignment, and the default value will be used
fn()

// Random number in range
// Define the function. The default values of the two numbers are set to 0 and 255 respectively
const randomNum = (a = 255, b = 0) => Math.floor(Math.random() * (Math.abs(a - b) + 1)) + Math.min(a, b)
console.log(randomNum(10, 100))

5. ES6 - deconstruction assignment

Overview of deconstruction assignment:

Deconstruction assignment is an extension of the assignment operator.

It is a method of pattern matching for arrays or objects, and then assigning values to variables in them. The code is concise and easy to read, and the semantics is clearer; It also facilitates the acquisition of data fields in complex objects.

Deconstruction model:

ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called {deconstructing.

In deconstruction, the following two parts are involved:

The source of deconstruction, deconstructing the right part of the assignment expression;

Deconstruct the target, deconstruct the left part of the assignment expression;

+Purpose: quickly get some data from objects or arrays
+Divided into two categories
1. Deconstruct array
2. Deconstruction object

const arr = [10, 20, 30]
// Requirement: define three variables separately to obtain three data
// The original way is not convenient enough
const n1 = arr[0]
const n2 = arr[1]
const n3 = arr[2]

1. Deconstruct array
+Quickly get some data from the array
+Note: use [] to deconstruct the array
+Syntax: const [variable 1, variable 2, variable 3,...]= array
= > assign values to the variables in the deconstruction according to the index of the array

// 1. Use deconstruction array to get
// n1 gets the data at [0] in the arr
// n2 obtains the data of [1] position in the arr
// n3 gets the data at [2] in the arr
const [ n1, n2, n3 ] = arr
console.log(n1, n2, n3)	    // Print = > 100 200 300

+Extension: Deconstruction of multidimensional arrays
= > deconstruction looks like the original array
- > how to write an array and how to write a deconstruction
- > replace data with variables

// Extension: Deconstruction of multidimensional arrays
const arr = [1, 2, [3, 4, [5, 6, [7, 8, [9, [10]]]]]]
console.log(arr)    // (3) [1, 2, Array(3)]
// Requirements: define variables to get 9 this data
const a = arr[2][2][2][2][0]
console.log(a)    // 9
// Deconstruction:
	  const [a, b, [c, d, [e, f, [g, h, [i, [j]]]]]] = arr
console.log(i)                       //  9
// 2. Deconstruction object
const obj = { name: 'Jack', age: 18, gender: 'male' }
// before
const name = obj.name
const age = obj.age
const gender = obj.gender
console.log(name, age, gender)	// Jack 18 male

2. Deconstruction object
+Quickly get some data from the object
+Note: Deconstruction objects use {}
+Syntax: const {key name 1, key name 2, key name 3,...}= object
= > define variables in sequence according to the key name, and obtain the specified members from the object

// deconstruction
const { name, age, gender } = obj
console.log(name, age, gender)	// Jack 18 male

=>An alias when deconstructing
+Alias: const {key name: alias, key name 2: alias} = object
->Note: when you have an alias, the original key name cannot be used as a variable name. You need to use this alias

// 2-2.  An alias when deconstructing
const obj = { name: 'Jack', age: 18, gender: 'male' }
// Const {name} = obj is equivalent to const name = obj name
// Const {Name: n} = obj is equivalent to const n = obj name
const { name: n, gender, age: a } = obj
console.log(n, gender, a)	// Jack male 18

+Extending: deconstructing multidimensional objects
= > deconstruction will look like the original object, and the data will be replaced with variables

// Extending: deconstructing multidimensional objects
const obj = {
  name: 'Jack',
  age: 18,
  info: {
	weight: 180,
	height: 180,
	data: {
	  desc: 'The man is lazy, Nothing left',
	  hobby: [ 'having dinner', 'sleep' ]
	}
  }
}

// I want to get it to sleep
// deconstruction
const {
  name: n,
  age,
  info: {
    weight: w,
    height: h,
    data: {
      desc,
      hobby: [ a, b ]
    }
  }
} = obj

console.log(h)	// 180
console.log(b)	// sleep

Interview case:

//Pit 1:

const obj = { name: 'Jack', age: 18, gender: 'male' }
const { age: a } = obj
// Equivalent to executing const a = obj age
console.log(a)    // 18
console.log(age)  // Error printing = > age is not defined
// When you alias a data, the original key name can no longer be used as a variable name. It is the alias
const obj = { name: 'Jack', age: 18, gender: 'male' }
const { name: n } = obj
// Equivalent to const n = obj name
console.log(n)	 // Jack
console.log(name)// No error = > empty string (''), because a name attribute is born in Window
//Only name can be used alone, because Window is born with such a property and is locked to string type
name = 18 
console.log(typeof name)  // Print = > string

  =>  

//Pit 2:

// const defined constants cannot be modified
// The value accepted by obj is the address of an object data type
// Under what circumstances is it called to modify the obj value and change the address
const obj = { name: 'Jack' }
//Instead of modifying the value of obj, the value in the space of obj is modified
obj.name = 'Rose'
console.log(obj.name)	// Rose
//(when you re const obj = {...} Time) 
//An error will be reported: identifier 'obj' has already been declared

//Pit 3:

for (var i = 0; i < 3; i++) {
  // asynchronous
  setTimeout(() => {
	console.log(i)		// Print = > three 3
  }, 0)
}
/*
  Global definition variable i

  Start cycle
	i === 0
	  => Define a timer. Is the timer processing function executed? = > No, wait until the synchronization code is executed
	  => Put a function () into the queue = > {console. Log (I)}
	i === 1
	  => Define a timer
	  => Put a function () into the queue = > {console. Log (I)}
	i === 2
	  => Define a timer
	  => Put a function () into the queue = > {console. Log (I)}
	i === 3
	  End of cycle

  At this time, the asynchronous code will not be executed until all synchronous codes are executed
	=> Directly execute the three functions in the queue
	=> Print three times on the console i
*/

/ / excavation depth of Pit 3:

// Block level scope: any {} that can write code segments will limit the scope of variables
for (let i = 0; i < 3; i++) {
  // asynchronous
  setTimeout(() => {
	console.log(i)		// Print = > 0 1 2
  }, 0)
}
/*
  Open page

  Loop start = > note: variables defined by let will be locked by {}
  {
	i === 0
	A timer processing function is prepared. In the queue, () = > console log(i)
  }
  {
	i === 1
	A timer processing function is prepared. In the queue, () = > console log(i)
  }
  {
	i === 2
	A timer processing function is prepared. In the queue, () = > console log(i)
  }
  {
	i === 3
	End of cycle
  }

  After all synchronous codes are executed, start executing asynchronous codes = > Print 0 1 2
*/

/ / re excavation of Pit 3:

for (let i = 0; i < 3; i++) {
  // asynchronous
  setTimeout(() => {
	console.log(i)	// Print after error = > 0 1 2
  }, 0)
}
console.log(i) // Error = > I is not defined
// 0 1 2 will continue to be printed
// Because the timer is set before an error is reported

It doesn't mean that an error will interrupt the execution of the program, but why does the subsequent code still print out the results?

Because setTimeout is the code in your asynchronous queue, which is ready to execute before you report an error

It just does not execute the code after the error is reported, but this sentence is the code before the error is reported, so it will still print 0 1 2

Because the timer is set before the error is reported, the browser will end before the error is reported,

Execute all your prepared code

For example, we can think of it as you command a person. When this person does something wrong, he will no longer continue to do things,

Here you tell him: set an alarm clock, ring it in 1} second, set another one, and ring it in 1 minute

Then when the man went to get hot water, he accidentally burned his hand, so he couldn't do anything again,

But he has set the alarm clock, and it will ring at the time, so it has nothing to do with whether he can work or not

6. ES6 - extension operator

+There is an operator in ES6 syntax
+Expand merge operator
+There are two meanings
1. Expand = > Expand operator (...)
2. Merge = > merge operator (...)
+ ...
= > it is mainly used to operate the operation symbols of arrays and objects
1. Expand operator
=>You can expand objects or arrays
=>Mostly used for arrays
=>When you use the position of an array or object or function argument, it is called expansion operation
=>If the object is expanded, the {} of the object is removed
=>If the array is expanded, the [] of the array is removed

// 1. Expand operator
const arr = [ 100, 200, 300 ]
// If I want to print 100 200 300 on the console
console.log(arr)	// (3) [100, 200, 300]
console.log(100, 200, 300)// 100 200 300
console.log(...arr)	  // 100 200 300

const arr2 = [...arr, 400, 500]
console.log(arr2)	// (5) [100, 200, 300, 400, 500]

const res = Math.max(...arr)
console.log(res)	// 300
// Expand objects
const o1 = { name: 'Jack', age: 18 }
const o2 = {
  gender: 'male',
  ...o1
}
const o3 = {
  ...o2,
  score: 200
}
console.log(o1, o2, o3)


2. Merge operator
=>Used to merge multiple data
=>When you use the position of a formal parameter in a deconstruction array or function, it is called a merge operation
=>When this symbol is written at the position of the formal parameter of the function, it is called the merge operator
=>Get arguments from the current parameter position until the end
=>Note: the merge operator must be written in the last bit

// 2. Merge operator
const arr = [ 100, 200, 300 ]
// Use merge operators in Deconstruction
// Assign [0] in arr to a
// All contents from [1] to the end of arr are assigned to b and appear in the form of a new array
// Note: the merge operator must be written in the last position
const [ a, ...b ] = arr
console.log(a)	// 100
console.log(b)	// (2) [200, 300]

// Use at function parameter locations
// Assign the first argument to a
// All the remaining arguments are given to b in the form of a new array
// Note: the merge operator must be written in the last position
function fn(a, ...b) {
  console.log(a)	// 100
  console.log(b)	// (2) [200, 300]
}
fn(100, 200, 300)
// The arrow function has a feature that there are no arguments
// We can use Merge one arguments
const fn = (...arg) => {
  console.log(arg)
}
fn(10, 20, 30)	// (3) [10, 20, 30]

7. ES6 - object abbreviation syntax

ES6 - object shorthand syntax (not mandatory)
1. when key is as like as two peas and value is value, and when a variable is a variable,
= > value and colon (:) can be omitted
2. When the value of a key is a function and not an arrow function
= > you can directly omit the function keyword and colon (:) without writing

// 1. key is the same as value
const day = 12
const hours = 23
const minutes = 33
const seconds = 25
const obj = {
  day, // Equivalent to you wrote day: day
  hours,
  minutes,
  seconds,
  // key and value are as like as two peas.
  // But value is not a variable
  data: 'data'
}
console.log(obj)

// 2. Function abbreviation
const obj = {
  name: 'I am obj object',
  // f1 is a function, but not an arrow function, which can be abbreviated
  f1: function () { console.log(arguments) },
  // f2 although it is a function, it is an arrow function and cannot be abbreviated
  f2: () => { console.log(arguments) },
  // f3 is a function and not an arrow function
  f3 () { console.log(arguments) },
  f4 () {
	// ...
  }
}
obj.f1(1, 2, 3)
obj.f3(10, 20, 30)

8. ES6 - Modular Development

Historical evolution of development:
=>Earliest: a js file
- > each html file corresponds to a js file
=>Later: extract the repeated functions within a project
- > write a separate js file
=>Then:
- > decide to split the files one by one according to the function
- > A.js: dedicated to various functions of the top navigation bar
- > B.js: specialized in secondary menu
- > c.js: specialized in search engine
- > d.js: left sidebar
- > e.js: rotation chart
- > finally, an integrated js file is prepared for each page
+ is specifically used to combine the number of js file modules used in this page
- > at this time, we call each js file a module
+ the complete function of the page is completed by modules one by one
- > it's called modular development
Rules for modular development:
1. If you want to use the modular development syntax of ES6
= > the page must be opened on the server
= > cannot be opened locally
= > vs code download Plug-in, Live Server (will help you configure a virtual server)
= > when opening the page, right-click open with live server
- > shortcut key, alt + l, press alt + o again


2. When you use modular grammar
= > each js file is an independent file scope
= > all variables and methods in this file can only be used in this file
= > other files cannot be used
= > if you want to use, you need to export
3. Each js file cannot use any variables inside other js files
= > if you want to use
= > then you need to import the file
Syntax: export and import
+Export syntax:
export default {what you want to export}
+Import syntax:
import variable from 'js file'

<!-- Only one needs to be introduced index.js file -->
<!-- because index.js Other modules that need to be used are used in the file -->
<!-- If your page introduces a user ES6 Modular syntax js file -->
<!-- Must be opened on the server, And give script Add a label type="module" Properties of -->
<script src="./js/index.js" type="module"></script>

9. ES6 - class syntax

+Class is the content specifically used to create objects
+Explanation: how ES6 writes constructors
+Private: that's the constructor

Syntax:
+Class class name {}
= > class: defines the keyword of the class
= > class name: the name of the class
= > {}: all contents contained in this class
+Content written in class {}
  1. construcor ( ) { }
= > constructor body equivalent to ES5
  2. Methods on constructor prototypes
= > write directly after the constructor
= > method name () {}
= > indicates a method added to the prototype
= > equivalent to constructor prototype. Method name = function() {}
  3. Class
= > static method name () {}
= > static variable = value
be careful:
+Because the essence of a constructor is a function, it can be called as an ordinary function
+However, the essence of a class is a class, not a function, so it cannot be called as an ordinary function

// ES5 write constructor
function Person() {
  this.age = 18
}
Person.prototype.sayHi = function () { console.log('hello world') }
// hello world
const p = new Person()
p.sayHi()
console.log(p)		// Person {age: 18}
// Constructor is called as a normal function
Person()

// Writing of ES6
class Student {
  constructor () {
	// This position is equivalent to the constructor body of your ES5
	this.age = 20
  }
  // Method of writing directly on Prototype
  sayHi () { console.log('hello student') }// hello student
}
const s = new Student()
s.sayHi()
console.log(s)	// Student {age: 20}
// If it is not used with the new keyword and the class is directly executed as an ordinary function, an error will be reported
// Use of class: because the essence of class is not a function
// It must be used in conjunction with the new keyword
Student()

 

How to distinguish between static methods and prototype methods
+In writing
= > if you want to write a method to be used by an instance in the future, write it as a prototype method
= > if you want to write a method for your class to use in the future, write it as a static method
= > if you want to write a prototype method, write it directly (method name () {})
= > if you want to write a static method, write it directly (static method name () {})

// Class of ES6
class Person {
  // Constructor body
  constructor (name, age) {
	this.name = name
	this.age = age
  }
  // Method sayHi on Prototype
  // It is added to the prototype of Person and is specially used for all instances of this class
  sayHi () {
	console.log('hello world')
  }
  sayHi2 () {}
  sayHi3 () {}
  // Add static methods and properties
  // Treat Person as an object and add methods to yourself
  // Not for instance use, and instances cannot be used
  // It's for your own use
  static fn1 () { console.log('I am Person Class') }
  static a = 100
}

+In use
= > if you write (method name () {})
= > when you use it in the future, you should rely on the instance object of this class to call it
    -> const p1 = new Person( )
    -> p1. Method name ()
= > get and call in the form of this within the method
- > method name () {this.xxx}
= > if you write (static method name () {})
= > in the future, you should rely on the class name to call
- > class name Method name ()

// Constructor for ES5
function Person(name, age) {
  this.name = name
  this.age = age
}
// Method on Prototype
// It is added by the constructor and used exclusively for the instance, not for the function itself
Person.prototype.sayHi = function () { console.log('hello world') }
// Because Person is a constructor, you can create objects
// It needs to be used in conjunction with the new keyword
const p1 = new Person('Zhang San', 18)
console.log(p1)		// Person {name: "Zhang San", age: 18}
// Because Person is essentially a function, it can also be used without the new keyword
// It just doesn't have the ability to automatically create objects, but it's not wrong
// Add the contents of the function body to Window (this points to Window)
const p2 = Person('Li Si', 20)
console.log(p2)		// undefined
// Because Person is not only a function, but also an object
// Some key value pairs can be stored as objects
// In fact, the function identity of Person does not conflict
// When you treat Person as an object and add some members
// Note: it is not for the instance, and the instance cannot be used. It is for the function itself
// We call the methods and properties used by the function itself static properties and methods of the function
// (that is, take the function as an object and add properties and methods to yourself for your own use)
Person.a = 100
Person.sayHi2 = function () { console.log('Person Your own way') }
console.dir(Person)	// ƒ Person(name, age)
// Equivalent to
const obj = {
  name: 'Jack',
  sayHi2: function () { }
}

 

Why do you write constructors in ES5
= > I like the ability to create objects
= > for high encapsulation, write this function once
= > it will be much more convenient when finished in the future
= > the general constructor will not be used with new and will not be used as an ordinary function

In ES6, make some evolution
= > removed his ability to call as an ordinary function
= > after it is removed, it can no longer be called a constructor
= > give yourself a new name, called the class
= > because of evolution, there must be some benefits and changes

Originally written as
    function Person( ) {
/ / constructor body
    }
Now write
    class Person {
      constructor ( ) {
/ / "constructor body"
      }
    }

The method on the prototype was originally written as
    Perosn.prototype.a = function ( ) { }
The method on the prototype is now written as
    class Person {
      conctructor ( ) { ... }

      a ( ) { }
      b ( ) { }
    }

The static method was originally written as
    Person.c = function ( ) { }
    Person.d = function ( ) { }
The static method is now written as
    class Person {
      constructor ( ) { ... }

      a ( ) { }

      static c ( ) { }
      static d ( ) { }
    }

Integration

  ES5 :
    function Person( ) { }

    Person.prototype.a = function ( ) { }

    Person.c = function ( ) { }

  ES6 :
    class Person {
      constructor ( ) { }

      a ( ) { }

      static c ( ) { }
    }

10. Legend:

Topics: Front-end ECMAScript