JavaScript advanced class ES6 → ES11 (9)


Reference video: Shang Silicon Valley Web front-end ES6 tutorial, covering ES6-ES11
supporting code: https://gitee.com/Augenstern-creator/kuang-study-es6
Insert image description here

1. class class

  • ES6 provides a writing method that is closer to traditional languages ​​and introduces the concept of Class as a template for objects.
  • Classes can be defined through the class keyword.
  • Basically, the ES6 class can be regarded as just a syntactic sugar. Most of its functions can be achieved by ES5. The new class writing method only makes the writing of the object prototype clearer and more like the syntax of object-oriented programming.

Knowledge points:

  • classdeclare class
  • constructorDefine constructor initialization
  • extendsInherit from parent class
  • superCall parent constructor
  • staticDefine static methods and properties
  • Parent class methods can be overridden

Let’s first look at the syntax of the ES5 constructor to instantiate an object as follows:

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

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

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

Let’s look at the syntax of ES6 instantiated objects as follows:

//class
class Shouji{
    
    
    //构造方法 名字不能修改
    constructor(brand, price){
    
    
        this.brand = brand;
        this.price = price;
    }

    //添加方法必须使用该语法, 不能使用 ES5 的对象完整形式
    call(){
    
    
        console.log("我可以打电话!!");
    }
}

let onePlus = new Shouji("小米", 1999);

console.log(onePlus);

Insert image description here

1.1. Static members of class

  • staticThe modified attribute belongs to the class, not the object
class Phone{
    
    
    //静态属性
    static name = '手机';
    //静态方法
    static change(){
    
    
        console.log("我可以改变世界");
    }
}

let xiaomi = new Phone();
console.log(xiaomi.name);		// undefined
console.log(Phone.name);		// 手机
console.log(Phone.change());    // 我可以改变世界

1.2. Class inheritance

  • In ES5, constructors are used to implement inheritance. The code is as follows
<script>
    //手机
    function Phone(brand, price){
      
      
        this.brand = brand;
        this.price = price;
    }

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

    //智能手机
    function SmartPhone(brand, price, color, size){
      
      
        Phone.call(this, brand, price);
        this.color = color;
        this.size = size;
    }

    //设置子级构造函数的原型
    SmartPhone.prototype = new Phone;
    SmartPhone.prototype.constructor = SmartPhone;

    //声明子类的方法
    SmartPhone.prototype.photo = function(){
      
      
        console.log("我可以拍照")
    }

    SmartPhone.prototype.playGame = function(){
      
      
        console.log("我可以玩游戏");
    }

    const chuizi = new SmartPhone('锤子',2499,'黑色','5.5inch');

    console.log(chuizi);

</script>
  • In ES6, extends is used to implement inheritance . The code is as follows
class Phone{
    
    
    //构造方法
    constructor(brand, price){
    
    
        this.brand = brand;
        this.price = price;
    }
    //父类的成员属性
    call(){
    
    
        console.log("我可以打电话!!");
    }
}

// 子类智能手机继承父类
class SmartPhone extends Phone {
    
    
    //构造方法
    constructor(brand, price, color, size){
    
    
        super(brand, price);// 相当于调用父类的构造方法:Phone.call(this, brand, price)
        this.color = color;
        this.size = size;
    }

    photo(){
    
    
        console.log("拍照");
    }

    playGame(){
    
    
        console.log("玩游戏");
    }

    // 子类重写父类方法
    call(){
    
    
        console.log('我可以进行视频通话');
    }
}

const xiaomi = new SmartPhone('小米',799,'黑色','4.7inch');
// console.log(xiaomi);
xiaomi.call();				// 	我可以进行视频通话
xiaomi.photo();				//  拍照
xiaomi.playGame();			//  玩游戏

1.3. Get and set methods of classes

// get 和 set
class Phone {
    
    
    // 当访问price属性时候调用 get 函数
    get price() {
    
    
        console.log("价格属性被读取了");
        return 'iloveyou';
    }

    // 当对 price 进行赋值时候会调用 set函数
    set price(newVal) {
    
    
        console.log('价格属性被修改了');
    }
}

//实例化对象
let s = new Phone();
s.price; // 价格属性被读取了
s.price = 'free'; // 价格属性被修改了

2. Numerical expansion

2.1、Number.EPSILON

  • Number.EPSILON is the minimum precision expressed in JavaScript
  • The calculation of floating point numbers is often imprecise. With the help Number.EPSILONof
// Number.EPSILON 进行浮点数的计算
function equal(a, b) {
    
    
    if (Math.abs(a - b) < Number.EPSILON) {
    
    
        return true;
    } else {
    
    
        return false;
    }
}
console.log(0.1 + 0.2 === 0.3);             // false
console.log(equal(0.1 + 0.2, 0.3))          // true

2.2. Binary and octal

ES6 provides new ways of writing binary and octal values, represented by the prefixes 0band respectively.0o

//1. 二进制和八进制
let b = 0b1010;
let o = 0o777;
let d = 100;				// 十进制
let x = 0xff;				// 十六进制
console.log(x);

2.3、Number.isFinite

  • Number.isFiniteCheck whether a number is a finite number
console.log(Number.isFinite(100));			// true
console.log(Number.isFinite(100/0));		// false
console.log(Number.isFinite(Infinity));		// false

2.4、Number.isNaN

  • Number.isNaNCheck if a value is NaN
console.log(Number.isNaN(123));   // false

2.5、Number.parseInt、Number.parseFloat

  • Number.parseInt, Number.parseFloatstring to integer
console.log(Number.parseInt('5211314love'));			// 5211314
console.log(Number.parseFloat('3.1415926神奇'));		   // 3.1415926

2.6、Number.isInteger

  • Number.isIntegerDetermine whether a number is an integer
console.log(Number.isInteger(5));					// true
console.log(Number.isInteger(2.5));					// false

2.7、Math.trunc

  • Math.truncErase the decimal part of the number
console.log(Math.trunc(3.5));				// 3

2.8、Math.sign

  • Determine whether a number is positive, negative or zero
console.log(Math.sign(100));				// 1代表整数
console.log(Math.sign(0));					// 0代表零
console.log(Math.sign(-20000));				// -1代表负数

3. Object method extension

3.1、Object.js

  • Object.is determines whether two values ​​are strictly equal, which is ===basically consistent with the behavior
console.log(Object.is(120, 120));//true
console.log(Object.is(NaN, NaN));//true
console.log(NaN === NaN);//false 

3.2、Object.assign

  • Object.assignMerge of objects
const config1 = {
    
    
    host: 'localhost',
    port: 3306,
    name: 'root',
    pass: 'root',
    test: 'test'
};
const config2 = {
    
    
    host: 'http://atguigu.com',
    port: 33060,
    name: 'atguigu.com',
    pass: 'iloveyou',
    test2: 'test2'
}
// config2 对象覆盖 config1 对象,相同属性覆盖,不同属性合并
console.log(Object.assign(config1, config2));

3.3、Object.setPrototypeOf 和Object.getPrototypeOf

  • Object.setPrototypeOfSet prototype object
  • Object.getPrototypeOf Get the prototype object
const school = {
    
    
    name: '尚硅谷'
}
const cities = {
    
    
    xiaoqu: ['北京','上海','深圳']
}
// 设置给 school 原型对象加上 cities
Object.setPrototypeOf(school, cities);
// 获取 school 的原型对象
console.log(Object.getPrototypeOf(school));
console.log(school);

4、ES7

4.1、Array.prototype.includes

  • includesThe method is used to detect whether an array contains an element and returns a Boolean value.
// Array.prototype.includes: 检测数组中是否包含某个元素
const arr = [1,2,3,4,5];
console.log(arr.includes(1)); // true
console.log(arr.includes(6)); // false

4.2. Exponential operator

The exponential operator was introduced in ES7 **, which can be used to implement exponentiation operations. The function is Math.powthe same as the result.

console.log(2 ** 10); // 1024
console.log(Math.pow(2,10)); // 1024

5、ES8

5.1, async and await

The combination of async and await syntax can make asynchronous code behave like synchronous code

async

  • The return value of the async function is a promise object
  • The result of the promise object is determined by the return value of the async function execution
// async 使得异步操作更加方便,在方法前面加上 async 关键字
// async 会返回一个 Promise 对象
async function f1(){
    
    
    // 返回字符串,只要返回的不是 Promise 类型,则这个结果就是一个成功状态的 Promise 对象
    return  '林晓';
}

async function f2(){
    
    
    // 返回的若是成功状态的 Promise 类型,则 result2 就是一个成功状态的 Promise 对象
    return new Promise((resolve,reject) => {
    
    
        resolve('成功');
    })
}

// result1 是一个 Promise 对象
const result1 = f1();
const result2 = f2();

await:

  • await must be written in async function
  • The expression on the right side of await is generally a promise object
  • await returns the value of promise success
  • If await's promise fails, an exception will be thrown, which needs to be captured and processed through try...catch.
// 一般 async 函数返回的都是 Promise 对象,所以我们这里创建Promise对象
const p = new Promise(((resolve, reject) => {
    
    
    resolve("成功状态");
}));
// await 要放在 async 函数中
async function  main(){
    
    
    // await返回的是 promise成功的值
    let result = await p;
    console.log(result); // 成功状态
}
// 调用函数
main();

5.2、Object.values 和 Object.entries

  • Object.keys()Method returns all keys of the object
  • Object.values()Method returns all values ​​of the object
  • Object.entries()method returns
// 声明对象
const school = {
    
    
    name: "尚硅谷",
    cities: ['北京','上海','深圳'],
}

// 获取对象所有的键
console.log(Object.keys(school)); // [ 'name', 'cities' ]
// 获取对象所有的值
console.log(Object.values(school)); // [ '尚硅谷', [ '北京', '上海', '深圳' ] ]
// entries 获取对象所有的键和值,是一个数组
console.log(Object.entries(school)); // [ [ 'name', '尚硅谷' ], [ 'cities', [ '北京', '上海', '深圳' ] ] ]

// 创建Map,我们可以把 entries 获取的数组放入 Map 中
const m = new Map(Object.entries(school));
console.log(m.get('cities')); // [ '北京', '上海', '深圳' ]

5.3、Object.getOwnPropertyDescriptors

  • Object.getOwnPropertyDescriptors: This method returns a description object of all its own properties of the specified object.
// Object.getOwnPropertyDescriptors 返回对象属性的描述对象
console.log(Object.getOwnPropertyDescriptors(school));
/**
 *
 * {
      name: {
        value: '尚硅谷',
        writable: true,
        enumerable: true,
        configurable: true
      },
      cities: {
        value: [ '北京', '上海', '深圳' ],
        writable: true,
        enumerable: true,
        configurable: true
      }
    }
 */

6、ES9

6.1. Rest/Spread attributes

Rest parameters and Spread expansion operators have been introduced in ES6, but ES6 only targets arrays. In ES9, rest parameters and spread operators like arrays are provided for objects.

function connect({
     
     host,port,...user}){
    
    
    console.log(host); //127.0.0.1
    console.log(port); //3306
    console.log(user); //{ username: 'root', password: 'root', type: 'master' }
}

connect({
    
    
    host: '127.0.0.1',
    port: 3306,
    username: 'root',
    password: 'root',
    type: 'master'
});

7、ES10

7.1、Object.fromEntries

  • Object.entries():Convert object into two-dimensional array
// 先回顾一下 ES8 的 `Object.entries` 可以将一个对象转化为二维数组
let people = {
    
    
    'name': '贺欣',
    'age': 20
}
// 将 people 对象转化为二维数组
const arr = Object.entries(people);
console.log(arr); // [ [ 'name', '贺欣' ], [ 'age', 20 ] ]
  • Object.fromEntries(): Convert a two-dimensional array into an object
    • The parameter is a two-dimensional array or a map object
// Map
const m = new Map();
m.set('name','林晓');
m.set('age',20);
// ES10 中的 Object.fromEntries 可以将二维数组转化为对象
const result = Object.fromEntries(m);
console.log(result);
// { name: '林晓', age: 20 }

7.2, trimStart and trimEnd

  • trim: Clear whitespace characters on both sides

  • trimStart: Clear left blank characters

  • trimEnd: Clear the blank characters on the right

let str = '    iloveyou   ';

console.log(str);
// 清除左侧空白
console.log(str.trimStart());
// 清除右侧空白
console.log(str.trimEnd());

7.3, flat and flatMap

  • flat(): Convert a multidimensional array into a low-dimensional array
    • Parameter is depth
// 二维数组
const arr = [1,2,3,4,[5,6]];
// 将二维数组转化为一维数组
console.log(arr.flat(1)); //[ 1, 2, 3, 4, 5, 6 ]

// 三维数组
const arr1 = [1,2,3,4,[5,6,[7,8,9]]];
// 将三维数组转化为二维数组
console.log(arr1.flat(1)); // [ 1, 2, 3, 4, 5, 6, [ 7, 8, 9 ] ]
// 将三维数组转化为一维数组
console.log(arr1.flat(2)); // [1,2,3,4,5,6,7,8,9]

7.4、Symbol.prototype.description

  • Returns the string description of Symbol
// 创建Symbol
let s = Symbol('小林');
console.log(s.description); // 小林

8、ES11

8.1. Private attributes

  • #: private property
class Person{
    
    
  // 公有属性
  name;
  // 私有属性
  #age;
  #weight;
  // 构造方法
  constructor(name,age,weight) {
    
    
    this.name = name;
    this.#age = age;
    this.#weight = weight;
  }

  // 对外暴露私有属性
  introduce(){
    
    
    console.log(this.name);
    console.log(this.#age);
    console.log(this.#weight);
}
}

// 实例化
const girl = new Person("小红",18,"45Kg");
console.log(girl.name);
//console.log(girl.#age); // 报错,私有成员不可访问
//console.log(girl.#weight); // 报错,私有成员不可访问
girl.introduce(); // 私有属性只有在类内部写有方法来调用

8.2、Promise.allSettled()

Promise.allSettled()Can be used to execute independent asynchronous operations in parallel and collect the results of these asynchronous operations. The function accepts an promisearray as a parameter.

const p1 = new Promise((resolve,reject) => {
    
    
  setTimeout(() => {
    
    
    resolve('商品数据 - 1')
  },1000)
});

const p2 = new Promise((resolve,reject) => {
    
    
  setTimeout(() => {
    
    
    resolve('商品数据 - 2')
  },1000)
});

// 调用 allSettled() 方法
const result = Promise.allSettled([p1,p2]);
console.log(result);

Promise.allSettled will never be rejected

Insert image description here

Even if we change one of the Promise statuses to failure, it allSettledwill still be in a successful status after calling.

8.3. Dynamic import

Dynamic import is a new syntax feature in JavaScript ES2019, which can achieve a more efficient loading method by importing code on demand . Dynamic import allows users to dynamically load modules at runtime, which is not possible with static import in ES6.

Through dynamic import, we can load the required modules only when the code is running , instead of loading all modules at once. In this way, we can avoid the problem of slow page loading caused by the page being too large. In practical applications, we can dynamically import as follows:

import(模块路径).then((模块) => {
    
    
    // 使用导入的模块
}).catch((error) => {
    
    
    // 捕获错误
});

8.4. BigInt type

//大整形
let n = 521n;
console.log(n,typeof(n)); // 521n bigint

// BigInt()函数:将普通整型转化为大整型
let n1 = 123;
console.log(BigInt(n));

// 主要用于大数值运算
let max = Number.MAX_SAFE_INTEGER;
console.log(BigInt(max) + BigInt(3)); // 9007199254740994n

8.5. Absolute global object globalThis

  • JavaScript can be executed in different environments, common ones include browsers, Web Workers, Node, Deno, etc.
  • In different environments, the methods of accessing global variables are different.
  • For example, on the browser, there are methods such as window, self, frames, etc.
/* 浏览器环境 */
window === self       // true
window === frames     // true

// 最顶层的窗口
window === parent     // true
window === window.top // true

window.msg = 'hello,world' // ok
console.log(msg).          // hello,world

The same code will report an error when run in Web Worker environment or Node environment.

/* Node */
window.msg = 'hello,world' // Uncaught ReferenceError: window is not defined
console.log(msg)           // Uncaught ReferenceError: msg is not defined

global.msg = 'hello,world' // ok
console.log(msg)           // hello,world

globalThisProvides a unified solution for accessing global variables. For example, in a browser environment, it will point to window, and in a Node environment, it will point to global.

/* 在绝大多数 JavaScript 运行环境下都能运行 */
globalThis.msg = 'hello,world'
console.log(msg);

Guess you like

Origin blog.csdn.net/Augenstern_QXL/article/details/133383045