ES6 learning - understand ES6 in one article

ES6 learning - understand ES6 in one article

Introduction to es6

The full name of ES is EcmaScript, which is the specification of scripting language, and an implementation of EcmaScript that is often written, so the new features of ES actually refer to the new features of JavaScript.

Why learn ES6

1. The ES6 version has the most changes and is a milestone.
2. ES6 has added many new grammatical features, making programming easier and more efficient
. 3. ES6 is the trend of front-end development and must be employed

ES6-let variable declaration and declaration characteristics

Declare variables:
let in es6
let attribute

  1. Variables cannot be declared repeatedly
    ES6let variables cannot be declared repeatedly
  2. Block-level scope [global scope, function scope, eval scope]
    let block scope
  3. There is no variable promotion [: the code will collect variables and functions in advance before execution, and assign initial values ​​​​null and undefined] let cannot be used before variable declaration, and var can be used before being declared.
    variable hoisting for var
    Let's variable promotion error
  4. does not affect the scope chain
    let does not affect the scope chain

The declaration of const and its characteristics

Variable declaration [declaring constants]
const declares a constant
Attention to the use of const

  1. Be sure to assign an initial value
    const assign initial value
  2. Unspoken rules, general constants use uppercase
    The unspoken rules of const
  3. Constant value cannot be modified
    Constants cannot modify the initial value
  4. Block-level scope
    const block scope
    5. Modifications to elements of arrays and objects are not counted as modifications to constants, and no error will be reported
    The const element modifies the array without error
    const modification value error

Struct assignment of ES6 variables

ES6 allows extracting values ​​from arrays and objects according to a certain pattern, and assigning values ​​​​to variables

  1. Array Destructuring
    Destructuring of es6 arrays
  2. Object deconstruction
    Destructuring of es6 objects
    Why object deconstruction?
    Let’s look at the code first:
    Why does es6 need to destructure single objects
    attribute deconstruction is less used, and method deconstruction is used more. If you don’t use method deconstruction, you need to write "zhao.xiaopin()" every time, which is more repetitive. Then you can deconstruct the object and call There is no need to write the form of "zhao.xxx" in front of the method;
    Method destructuring and calling
    under what circumstances should the deconstruction of the method be used:
    the new features are created to make it more convenient for developers. When the method is called frequently, you can think of using destructuring assignment at this time to make the code more concise.

ES6 template strings

ES6 introduces the emerging way of declaring stringsThe way es6 introduces strings

  1. es6 string declaration
    es6 string declaration
  2. Feature 1: A newline character can appear directly in the content.
    If there is a newline character before es6, an error will be reported [Grammar error]
    es6 string appears newline error error
    No error will be reported after es6 appears. Use "``" to solve the problem of grammatical error.
    es6 newline string
  3. Feature 2: variable splicing
    Splicing of es6 variables

Simplified writing of es6 objects

ES6 allows variables and functions to be directly written in braces as properties and methods of objects, simplifying the steps for programmers to write code.

  1. Variable form simplifies object writing
    Simplified writing of es6 objects
  2. Method declaration simplifies
    the cumbersome writing of object methods before es6
    How to write object methods before es6
    Simplified writing of object methods after es6
    Simplified writing of object methods after es6

ES6 arrow function and declaration features

es6 allows the use of [arrow] (=>) to define functions

  1. Declare a function using a raw method and a method using an arrow function
    The original method of declaring a functionArrow function declaration and call
  2. What is the difference between the characteristics of the arrow function declaration and the previous functions?

1. This is static. This always points to the value of this under the scope where the function is declared. The this value of the arrow function is static. No matter what method is used to call it, its this always points to the value of the function in the declaration The this value under the current scope.
Direct call: Arrow function this points to
call Method call: You can change the value of this inside the function. The following results show that call cannot change the direction of this in the arrow function.
call call arrow function
2. Arrow functions cannot be used as constructors to instantiate objects
Arrow functions cannot be used as constructors to instantiate objects
3. The arguments variable cannot be used [the special variable arguments inside the function is used to store actual parameters]
Arrow functions cannot use the arguments variable
4. Shorthand for arrow functions,
the first of the two cases: parentheses are omitted , can be omitted when there is only one formal parameter.
Arrow functions omit parentheses
The second is to omit curly braces. When the code body has only one statement, return must be omitted at this time, and the execution result of the word order is the return value of the function.
Arrow functions omit curly braces
Notes on using arrow functions:

1. Arrow functions are suitable for this-independent callbacks, timers, and array method callbacks
2. Arrow functions are not suitable for thi-related callbacks, event callbacks, and object methods

Default value setting for es6 function parameters

In es6, it is allowed to assign initial values ​​​​to function parameters

  1. The initial value of the formal parameter
    es6 assign initial value
    es6 In the formal parameter, one less NaN result is passed.
    es6 function calls formal parameters and pass less value
    es6 assigns the initial value to the function. If this parameter is not passed, the default value is the initial value.
    es6 assigns initial values ​​to function parameters
    Note: the parameters with default values ​​should generally be placed later (latent rule)

  2. Used in conjunction with destructuring assignment.
    es6 parameters combined with destructuring assignment
    If passed parameters are passed, if not passed, use the default value set.

Rest parameters in es6

es6 refers to the rest parameter, which is used to obtain the actual parameters of the function, and is used to replace arguments [get all the actual parameters when the function is called]

  1. The way es5 gets real parameters [returned object]
    The way es5 gets real parameters
  2. The rest parameter in es6 [returns an array]
    The rest parameter in es6 [returns an array]
    can use "filter", some every, map to return an array, which improves the flexibility of parameter processing.
  3. Note: If there are multiple parameters, the rest parameter must be placed at the end of the parameter.
    wrong usage:
    rest parameters

use correctly:
rest parameters

Introduction to es6 spread operator

The […] spread operator can convert an [array] into a comma-separated [parameter sequence].

  1. Example
    Pass without using ..., pass an array
    Introduction to es6 spread operator
    Pass with ...
    Introduction to es6 spread operator

Application of spread operator

  1. Merge of arrays
    es6 spread operator array merge
  2. array clone
    Array clone with es6 spread operator
  3. Convert pseudo array to real array
    The es6 spread operator converts a pseudo-array into a true array

Introduction and creation of es6-Symbol

  1. The introduction of symbol
    ES6 introduces a new primitive data type symbol, a unique value, which is the seventh data type of the javascript language and is an array type similar to strings.
  2. The characteristics of symbol

1. The value of symbol is unique and used to resolve naming conflicts.
Second, the value of symbol cannot be operated with other data.
3. The object properties defined by symbol cannot be traversed using the for...in loop, but you can use Reflect.ownKeys to get all the key names of the object


  1. The first way to create a symbol :
    Create Symbol

The second way to create: the symbol inside the brackets is just the sign of the symbol.
Symbol creation
The third way: 【Symbol.for()】, symbol.for is a global symbol table, if there is one, access the corresponding object, if not, create it.
Symbol creation

es6-objects add attributes of symbol type

Using symbols to add objects and properties, we can quickly and safely add objects to the game without destroying the original properties and methods.

  1. The first method of adding
    symbol add object
  2. The second addition
    Add an attribute of symbol type to an object

ES6-Symbol built-in values

In addition to defining the Symbol value used by itself, ES6 also provides many built-in Symbol values, pointing to the methods used internally by the language.
ES6-Symbol built-in values
ES6-Symbol built-in values
ES6-Symbol built-in values

  1. Symbol.hasInstance
    2.
  2. isConcatSpreadable
    insert image description here

es6-iterator

An iterator is an interface that provides a unified access mechanism for various data structures. Any data deconstruction can complete the traversal operation as long as the iterator interface is deployed.

  1. ES6 has created a new traversal command for ... of loop, the iterator interface is mainly for consumption by for ... or
  2. Data with native iterator interface can be traversed by for of, Array, Arguments, Set, map, string, typeArray, NodeList
  3. working principle
a. 创建一个指针,指向当前数据结构的起始位置。
b. 第一次调用对象的next方法,指针自动指向数据结构的第一个成员,
c. 接下来不断调用next方法,指针一直往后移动,知道只想最后一个成员。
d. 每调用next方法返回一个包含value和done属性的对象
**注意:需要自定义遍历数据的时候要想到迭代器**
  1. for...of loop [output key value]
    for...of loop
  2. for...in loop [output key name]
    for...in loop

Iterator application - custom traversal data

Customize the iterator to traverse the data according to the working principle of the iterator

 <script>
        //声明一个对象
        const banji = {
    
    
            name:"终极一班",
            stus:['小明','小天','小吴','小王',],
            [Symbol.iterator](){
    
    
                //索引变量
                let index = 0;
                //指向
                let _this = this;
                return {
    
    
                    next:function(){
    
    
                        if(index<_this.stus.length){
    
    
                            const result = {
    
    value:_this.stus[index],done:false}
                            //下标自增
                            index++;
                            //返回结果
                            return result;
                        }else{
    
    
                            return {
    
    value:undefined,done:true}
                        }
                    }
                }
            }
        }

        //遍历这个对象
        for(let v of banji){
    
    
            console.log(v);
        }
    </script>

Effect:
Iterator application - custom traversal data

es6-generator function declaration and call

The generator function is an asynchronous programming solution provided by ES6. The grammatical behavior is completely different from the traditional function. In fact, it is a special function for asynchronous programming. The pure callback function node \fs \ ajax \ mongodb was used
before

  1. Declaration and calling method:
    Generator declaration and calling method:
  2. The generator can use the yield statement
    yield can be counted as a separator of the function code
    Generators can use the yield statement
    The yield statement can be used as a separator, using the next call
    Generators can use the yield statement
  3. Using for-of to traverse generators
    Using for-of to traverse generators
  4. The generator's principle output explains what yield does:
    Schematic output of generators explaining what yield does

Parameter passing for ES6 generator functions

The next called by the generator can pass an actual parameter, and this actual parameter is the entire return result of the yield statement.

  1. pass parameters to the whole function
    es6 overall function parameter passing
  2. The next method can also pass parameters, and this parameter will be used as the return result of the previous yeild statement, and the second call returns the overall return result of the first yeild statement. . .
    Generator next method overall function parameter passing

es6 generator function instance

Asynchronous programming: file operation, network operation (ajax, request) database operation
Example: 1s output 111, 2s output 222, 3s output 333
layers of callbacks, it will become a callback
es6 generator function instance
hell The above code will enter the callback hell, the following will not work
insert image description here
Example 2, Simulate acquisition, user data, order data, product data
insert image description here
call:
Generator functions operate asynchronously

es6-promise learning and use

Introduction and basic use of es6-promise

Promise is a new solution for asynchronous programming introduced by ES6. Promise is a constructor that encapsulates asynchronous operations and can obtain odd success or failure results [Solve the callback hell problem]

  1. Promise constructor:Promise {excutor}{ }
  2. Promise.prototype.thenmethod
  3. Promise.prototype.catchmethod

1. Instantiate the Promise object.
The Promise object has three states, initialization, success, and failure.
Instantiate the promise object:

//实例化Promise对象【三个状态:初始化,成功,失败】
        const p = new Promise(function(resolve,reject){
    
    
            setTimeout(() => {
    
    
                let data = "数据库中的用户数据"
                //resolve调用
                resolve(data);
            }, 1000);
        });

Both success and failure of the call will execute the method of promise.then. The method of then has two parameters, both of which are values ​​of function type. Each function has a formal parameter. If the first function of then is executed successfully, it fails. The second execution parameter of the execution, the formal parameters of the two functions are value and reason, the successful one is called value, and the failed one is called reson.
Call then code:

/*
	 调用成功,就会调用promise对象的then方法,
     then方法接受两个参数,
     两个参数都是函数类型的值,每个函数都有一个形参,成功的叫做value,失败的叫做reason
     调到resolve代表成功,读取状态成功,then就会执行第一个回调函数代码
     如果读取状态失败,调用带有
  */
p.then(
	   function(value){
    
    
         console.log(value);
       },
       function(reason){
    
    
	   }
)

Successful call output:
Promise instantiated successfully
read failed example:

 const p = new Promise(function(resolve,reject){
    
    
            setTimeout(() => {
    
    
                //
                let data = "数据库中的用户数据"
                let err = "读取数据库失败"
                //resolve调用
                reject(err)
            }, 1000);
        });
        p.then(function(value){
    
    
            console.log(value);
        },function(reason){
    
    
            console.log(reason);
        })

Promise instantiation read failure returns result

es6-promise package read file

Native js output file content [request file content is asynchronous]

//引入fs模块
const fs = require('fs');

//调用方法读取文件
fs.readFile('./resources/1.md',(err,data)=>{
    
    
    //如果失败则抛出错误
    if(err) throw err;
    //如果没有出错,则输出内容
    console.log(data.toString());
})

Effect:
js reads files natively
use promise package to read the file:

//3.使用promise封装
const p = new Promise(function(resolve,reject){
    
    
    fs.readFile("./resources/1.md",(err,data)=>{
    
    
        //判断读取失败
        if(err) reject(err);
        //如果成功
        resolve(data)
    })
})
p.then(
    function(value){
    
    
        console.log(value.toString());
    },
    function(reason){
    
    
        console.log(reason);
    })

Effect:
Use promise package to read file
Use promise package to read file

es6-promise encapsulates Ajax requests

  1. Native Ajax request data
 <script>
        //接口地址:https://api.apiopen.top/getJoke

        //创建对象
        const xhr = new XMLHttpRequest();

        //初始化
        xhr.open("GET","https://api.apiopen.top/getJoke");

        //发送
        xhr.send();

        //4.绑定时间,处理响应结果
        xhr.onreadystatechange = function(){
    
    
            //判断
            if(xhr.readyState === 4){
    
    
                //判断响应状态吗 200-299
                if(xhr.status >= 200 && xhr.status < 300){
    
    
                    //表示成功
                    console.log(xhr.response);
                }else{
    
    
                    //如果失败
                    console.log(xhr.status);
                }
            }
        }
    </script>

Result of request success:
Native Ajax request data
Result of request failure:
Native Ajax request data
2. Promise encapsulates Ajax code

<script>
        //接口地址:https://api.apiopen.top/getJoke

        const p = new Promise((resolve,reject)=>{
    
    

        //创建对象
        const xhr = new XMLHttpRequest();

        //初始化
        xhr.open("GET","https://api.apiopen.top/getJoke");

        //发送
        xhr.send();

        //4.绑定时间,处理响应结果
        xhr.onreadystatechange = function(){
    
    
            //判断
            if(xhr.readyState === 4){
    
    
                //判断响应状态吗 200-299
                if(xhr.status >= 200 && xhr.status < 300){
    
    
                    //表示成功
                    resolve(xhr.response)
                }else{
    
    
                    //如果失败
                    reject(xhr.status);
                }
            }
        }
    });
    //指定回调
    p.then(
    function(value){
    
    
        console.log(value);
    },
    function(reason){
    
    
        console.log(reason);
    })
    </script>

Success effect:
Promise to encapsulate Ajax code
Failure effect:
Promise to encapsulate Ajax code
The processing method is different. It turns out that the results of success and failure are processed in the callback function. Promise is used to specify the callback through then after the asynchronous task. The structure is clear and there will be no problem of callback hell.

es6-Promise.prototype.then method

  1. then return result: the return result is determined by the callback result of the execution function. If the result returned in the callback function is a ||promise type attribute, the status is success, and the return value is the success value of the object.

  2. then returns a non-Promise object

//创建promise对象
   const p = new Promise((resolve,reject)=>{
    
    
       setTimeout(()=>{
    
    
          //resolve("请求成功")
          reject("请求失败")
       },1000)
   });

   //调用 then方法
   const result = p.then(value =>{
    
    
       console.log(value);
       return value;
   },reason =>{
    
    
       console.log(reason);
       return reason;
   })
   console.log(result);

The Promise.prototype.then method returns the result
The Promise.prototype.then method returns the result
Do not write returnthe return undefinedresult:
The Promise.prototype.then method returns the result
3. then returns the Promise object
then returns the Promise object, the state of the promise in then determines the state of an object returned by the then method, and the failure of the Promise in then determines the state of a failure returned by the then method.

//创建promise对象
   const p = new Promise((resolve,reject)=>{
    
    
       setTimeout(()=>{
    
    
          resolve("请求成功")
          //reject("请求失败")
       },1000)
   });

   //调用 then方法
   const result = p.then(value =>{
    
    
       return new Promise((resolve,reject)=>{
    
    
           resolve('ok')
       })
   },reason =>{
    
    
       console.log(reason);
   })
   console.log(result);

then returns the Promise object
then returns the Promise object
4. then throws an error
[if an error is thrown, this state is also a failed Promise state, and the value of the error is the value thrown]

//创建promise对象
   const p = new Promise((resolve,reject)=>{
    
    
       setTimeout(()=>{
    
    
          resolve("请求成功")
          //reject("请求失败")
       },1000)
   });

   //调用 then方法
   const result = p.then(value =>{
    
    
       //抛出错误
       throw new Error("出错啦")
   },reason =>{
    
    
       console.log(reason);
   })
   console.log(result);

Effect:
then throws an error
Since the then method can return a promise object, the then method can be called in a chain, and the chain call [when the then method specifies a callback, only one can be specified, and the problem of callback hell can be changed through a chain call]
format :

p.then(value=>{
    
    
    //异步任务
},reason=>{
    
    
 //异步任务
}).then(value=>{
    
    
     //异步任务
},reason=>{
    
    
 //异步任务
})

es6-promise practical exercise - multiple file content reading

        //回调地狱容易重名,很不容易被发现
  1. Do it the callback hell way
//引入fs模块
const fs = require("fs")

fs.readFile('./resources/1.md',(err,data)=>{
    
    
    fs.readFile('./resources/2.md',(err,data1)=>{
    
    
        fs.readFile('./resources/3.md',(err,data2)=>{
    
    
            let result = data+"\r\n"+data1+"\r\n"+data2
            console.log(result);
        });
    });
});

It can be found from the above code that the callback hell is easy to have the same name, and it is not easy to be found.
Promise implementation:

//使用promise来实现
const p = new Promise((resolve,reject)=>{
    fs.readFile("./resources/1.md",(err,data)=>{
        resolve(data);
    })
})
p.then(value=>{
    return new Promise((resolve,reject)=>{
        fs.readFile("./resources/2.md",(err,data)=>{
            resolve([value,data]);
        });
    });
}).then(value=>{
    return new Promise((resolve,reject)=>{
        fs.readFile("./resources/3.md",(err,data)=>{
            //压入
            value.push(data);
            resolve(value)
        });
    });
}).then(value=>{
    console.log(value.join('\r\n'));
})

Promise implements multiple file content reading

es6-Promise object catch method

catch is used to specify a callback for promise failure

The first method code:

 <script>
        const p = new Promise((resolve,reject)=>{
    
    
            setTimeout(()=>{
    
    
                //设置p对象的状态为失败,并且设置失败的值
                reject("出错啦")
            })
        })
        p.then(function(value){
    
    

        },function(reason){
    
    
            console.error(reason);
        })
    </script>

Effect:
The catch method in Promise

Second way code:

<script>
        const p = new Promise((resolve,reject)=>{
    
    
            setTimeout(()=>{
    
    
                //设置p对象的状态为失败,并且设置失败的值
                reject("出错啦")
            })
        })
        p.catch(function(reason){
    
    
            console.warn(reason);
        })
    </script>

The catch method in Promise

es6-collection introduction and API

set introduction

ES6 provides a new data structure Set (collection). It is similar to an array, but the values ​​of the members are all unique collections that implement the iterator interface, so you can use [extension operator] and [for…of…] to traverse

The properties and methods of the collection:
1) size: return the number of elements in the collection
2) add: add a new element and return the current collection
3) delete: delete the element and return a boolean value
4) has: check whether the collection contains a certain element, returns a boolean value

Simply understand Set through code:

   //声明一个set
    let s = new Set();
    //可以写入可迭代数据,可以去重
    let s2 = new Set(['大事儿','小事儿','坏事儿','小事儿','很多事儿','大事儿'])
    console.log(s,typeof s);
    console.log(s2);

Effects:
es6-collection introduction and API
Introductory code and effects for collection properties and methods

 //元素个数
    let s2 = new Set(['大事儿','小事儿','坏事儿','小事儿','很多事儿','大事儿'])
    console.log(s2.size);
    //向集合里添加新的元素
    s2.add("喜事儿")
    console.log("集合添加后有:"+s2.size+"个",s2);
    //删除元素
    s2.delete("坏事儿")
    console.log("集合删除后有:"+s2.size+"个",s2);
    //检测【检测集合中有没有该元素】
    console.log(s2.has('喜事儿'));
    //可以使用for...of...遍历
    for(let v of s2){
    
    
        console.log(v);
    }
    //清空集合
    s2.clear();
    console.log(s2);

Effect:
es6-collection introduction and API

es6-collection practice

Two arrays are already known:

let arr = [1,2,3,4,5,4,3,2,1,5,4,5,8,9,54,4,1]
let arr2 = [54,1,3,4,6,9,8]
  1. Array deduplication
 //1.数组去重
        let result = [...new Set(arr)]
        console.log(result);

Use setApi for array deduplication
2. Intersection of two arrays

//2.交集
    let arr2 = [54,1,3,4,6,9,8]
        let result2 = [...new Set(arr)].filter(item=>{
    
    
            let s2 = new Set(arr2)
            if(s2.has(item)){
    
    
                return true
            }else{
    
    
                return false
            }
        })
    console.log(result2);
    //简化版求交集
    let result3 =[...new Set(arr)].filter(item=>new Set(arr2).has(item))
    console.log(result3);

Use the Set API to find the intersection of arrays
3. The union of two arrays

//3.并集
        let result4 =[...new Set([...arr,...arr2])]
        console.log(result4);

Effect:
Use setAPI to find the union of two arrays and remove the duplicates
4. Find the difference of two arrays [inverse operation of intersection]

//4.差集
        let result5 = [...new Set(arr)].filter(item=>{
    
    
            let s2 = new Set(arr2)
            if(!s2.has(item)){
    
    
                return true
            }else{
    
    
                return false
            }
        })
      let result6 =[...new Set(arr)].filter(item=>!new Set(arr2).has(item))
    console.log(result5);
    console.log(result6);

Effect:Using the Set API to find the difference of two arrays

Introduction and API of es6-Map

ES6 provides a map data structure, which is similar to an object and a collection of key-value pairs, but the scope of "key" is not limited to strings, and various types of values ​​(including objects) can be used as keys, and map also implements the iterator interface , so you can use [extension operator] and [for...of...] to traverse, map attributes and methods:

  1. size Returns the number of elements in the map
  2. size is a new element, returns the current map
  3. get returns the key value of the key object
  4. has detects whether an element is contained in the map and returns a bollean value
  5. clear clears the collection, returns undefined,
    declares a Map and adds
 //声明 Map
    let m = new Map();

    //添加元素
    m.set('name','吴又可');
    m.set('change',function(){
    
    
        console.log("无用的方法");
    });
    console.log(m);

APIs
map adds a second method

 //声明 Map
    let m = new Map();

    //添加元素
    m.set('name','吴又可');
    m.set('change',function(){
    
    
        console.log("无用的方法");
    });
    let key = {
    
    
        school : "sgg"
    };
    m.set(key,['北京','上海','广州']);
    console.log(m);

Effect:
map API
Other APIs of map

//添加
    m.set(key,['北京','上海','广州']);
    
    //删除
    m.delete('name')
    console.log(m);

    //获取
    console.log(m.get('change'));
    console.log(m.get(key));

    //遍历
    for(let v of m){
    
    
        console.log(v);
    }

    //清空  
    m.clear();

Map's other APIs

es6-class class

ES6 provides a writing method that is closer to the traditional language, and introduces the concept of the Class class. As an object template, the class can be defined through the class keyword. Basically, the class of ES6 can be regarded as just a syntactic sugar. Most of it Function, es5 can do it, the new class writing method just makes the circular writing method of the object clearer, more like the syntax of object-oriented programming.

  1. Knowledge points:
    (1) class declares class
    (2) constructor defines constructor initialization
    (3) extends inherits parent class
    (4) static defines static methods and properties
    (5) super calls parent constructor
    (6) parent class method can be repeated Write

  2. Review the use of Es6 classes

 // 手机
    function Phone(brand,price){
    
    
        this.brand = brand;
        this.price = price;
    }

    //添加方法
    Phone.prototype.call = function(){
    
    
        console.log("我可以打电话");
    }

    //实例化对象
    let Huawei = new Phone('华为',5999);
    Huawei.call();
    console.log(Huawei);

Use effect:
The use of es5class
3. The use of es6 class

// class
    class Phone{
    
    
        //构造方法,名字不能修改,当实例化的时候会自动执行
        constructor(brand,price){
    
    
            this.brand = brand;
            this.price = price;
        }

        //方法必须使用该语法,不能使用es5的对象完整形式
        call(){
    
    
            console.log("我可以打电话");
        }
    }
    let onePlus = new Phone("huawei",4999);
    console.log(onePlus);

The effect of class usage in es6
The effect of class usage in es6

Static members in Class in es6

static members in es5

In es5, the properties of the instance object and the function object are not the same. The properties of the instance object are the same as the prototype object of the constructor. The implicit prototype of the instance object points to the prototype object of the constructor

 function Phone(){
    
    

    }
    Phone.name = "手机";
    Phone.change = function(){
    
    
        console.log("我可以改变世界");
    }
    Phone.prototype.size = "5.5inch"
    let nokia = new Phone();
    console.log(nokia.name);
    console.log(nokia.size);
    npkia.change();

Effect:
Static variables of es5

To be continued~

Guess you like

Origin blog.csdn.net/qq_42696432/article/details/121687088