Talk about the difference between ES5 and ES6

We all know that JavaScript is composed of three parts:

1. ECMAScript (core): specifies the components of the language => syntax, types, statements, keywords, reserved words, operators, objects

2. BOM (Browser Object Model): Supports access and operation of the browser window, and can control the browser to display parts other than the page.

3. DOM (Document Object Model): The entire page is mapped to a multi-layer node result. With the help of the API provided by DOM, any node can be deleted, added and modified
 

What is ES5?

The full name of ES5 is ECMAScript5, or ES5, which is the fifth revision of ECMAScripts (the fourth edition was abandoned because it was too complicated), also known as ECMAScript2009, and was standardized in 2009.

What is ES6?

ES6, full name ECMAScript 6.0, namely ES6, is the sixth revision of ECMAScripts, also known as ES2015, which was released in June 2015 and is the next version standard of JavaScript.

ES6 is mainly to solve the congenital deficiencies of ES5. Currently, the browser's JavaScript is the ES5 version, and most high-version browsers also support ES6, but only some of the features and functions of ES6 are implemented. ES6 is an improvement after ES5. Compared with ES5, it is more concise and improves development efficiency.

First, let’s talk about the features of ES5:

1. Strict mode: Strict mode, restricting some usages.

2. Array adding methods: there are every, some, forEach, filter, indexOf, lastIndexOf, isArray, map, reduce, reduceRight methods.

3. Object methods: Object.getPrototypeOf, Object.create, etc. methods.

  • Object.getPrototypeOf
  • Object.create
  • Object.getOwnPropertyNames
  • Object.defineProperty
  • Object.getOwnPropertyDescriptor
  • Object.defineProperties
  • Object.keys
  • Object.preventExtensions / Object.isExtensible
  • Object.seal / Object.isSealed
  • Object.freeze / Object.isFrozen

Second, let’s talk about the features of ES6:

1. Block-level scope => keyword let, constant const

In ES6, let and const are usually used to declare, let means variable, const means constant

◼️ Features

Both let and const are block scoped. Using the {} code block as the scope can only be used in the code block. There is no variable promotion, so you can only declare it before using it, otherwise an error will be reported. Within a code block, a variable is not available until it is declared. Syntactically, this is called the "temporal dead zone" (TDZ for short), and repeated declarations are not allowed within the same code block.

const declares a read-only constant, which needs to be assigned when it is declared. (If const is an object,

Objects contain values ​​that can be modified. Abstractly speaking, the address pointed to by the object cannot be changed, and

Variable members can be modified. )

2. Object extension

◼️ Shorthand for properties and methods

Shorthand for object literal properties

ES6 allows writing variables directly in objects. In this case, the attribute name is the variable name, and the attribute value is the value of the variable.

var foo = 'bar';

var baz = {foo}; // 等同于 var baz = {foo: foo};

Shorthand for object literal methods. Omit the colon and the function keyword

var o = {
  method() {
    return "Hello!";
  }
};

// 等同于

var o = {
  method: function () {
    return "Hello!";
  }
};

◼️ Object.keys() method

Get all the property names or method names of the object (excluding the content of the prototype), and return an array.

var obj={name: "john", age: "21", getName: function () { alert(this.name)}};

console.log(Object.keys(obj)); // ["name", "age", "getName"]

console.log(Object.keys(obj).length); //3

console.log(Object.keys(["aa", "bb", "cc"])); //["0", "1", "2"]

console.log(Object.keys("abcdef")); //["0", "1", "2", "3", "4", "5"]

◼️ Object.assign ()

The assign method combines the properties and methods of multiple original objects into the target object. Can receive multiple

number, the first parameter is the target object, and the following are source objects

var target = {}; //目标对象

var source1 = {name : 'ming', age: '19'}; //源对象 1

var source2 = {sex : '女'}; //源对象 2

var source3 = {sex : '男'}; //源对象 3,和 source2 中的对象有同名属性 sex

Object.assign(target,source1,source2,source3);

console.log(target); //{name : 'ming', age: '19', sex: '男'}

3. Destructuring assignment

◼️ Array destructuring assignment

Destructuring assignment is an extension to the assignment operator. It is a pattern matching for arrays or objects, and then assigning values ​​to the variables in it. In terms of code writing, it is concise and easy to read, and the semantics are clearer; it also facilitates the acquisition of data fields in complex objects. The value in the array will be automatically parsed into the variable that receives the value, and the destructuring assignment of the array must correspond one by one if

If there is no correspondence, it is undefined

let [a, b, c] = [1, 2, 3];

// a = 1 // b = 2 // c = 3

◼️ Object destructuring assignment

The destructuring assignment of an object is actually similar to the destructuring assignment of an array, but the array members of the array are ordered, while the properties of the object are unordered, so the simple understanding of the destructuring assignment of the object is that the structures on the left and right of the equal sign are the same.

let { foo, bar } = { foo: 'aaa', bar: 'bbb' }; // foo = 'aaa' // bar = 'bbb'

let { baz : foo } = { baz : 'ddd' };  // foo = 'ddd'

4. Spread operator

The spread operator allows an expression to be expanded somewhere. The spread operator can be used where there are multiple parameters (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignments).

let obj1 = {
 value1: 1,
 value2: 2
};
let obj2 = {...obj1
};
console.log(obj2); // {value1: 1, value2: 2}

The above usage is actually equivalent to

obj2 = {value1: 1, value2: 2}

The difference between the writing method of the expansion operator and obj2 = obj1the writing method of direct assignment is that if it is directly assigned, it is equivalent to the address of the memory space that 引用类型is only assigned , and when it changes, it will also change accordingly. Instead, if you use the wording method, since the attribute types in the object are all , it is equivalent to recreating an object. When a change occurs at this time, the object will not be affected. But only when its attributes are all basic types (or only one layer of deep copy is performed). If the attribute in the object still has a reference type, modify the value of the reference type in the attribute, and the attribute values ​​of both objects will be modified.obj1obj2obj1展开运算符obj1基本类型obj2obj1

let obj1 = {
 attri1: [3, 6, 0],
 attri2: 4,
 attri4: 5
};
let obj2 = {...obj1
};

obj2.attri2 = 888;
obj2.attri1[0] = 7;

console.log('obj1:', obj1);
console.log('obj2:', obj2);

Application of the spread operator

1. Using the spread operator in a function

function test(a, b, c){};

let arr = [1, 2, 3];
test(...arr);

2. Use the spread operator in array literals

let arr1 = [1, 2];
let arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]

// 使用push方法
let arr1 = [1, 2];
let arr2 = [3. 4];
arr1.push(...arr2); // [1, 2, 3, 4]

3. It is used for destructuring assignment. The expansion operator in destructuring assignment can only be used at the end, otherwise an error will be reported.

// 解构赋值中展开运算符只能用在最后。
let [a, b, ...c] = [1, ,2, 3, 4]
console.log(a, b, c) // 1, 2, [3, 4]

4. Class arrays become arrays

let oLis = document.getElementsByTagName("li");
let liArr = [...oLis];

5. Use the expansion operator in the object
The object expansion operator in ES7 allows us to manipulate objects more quickly:

let {x,y,...z}={x:1,y:2,a:3,b:4};
x; // 1
y; // 2
z; // {a:3,b:4}

Insert an object into another object:

let z={a:3,b:4};
let n={x:1,y:2,...z};
console.log(n); //{x:1,y:2,a:3,b:4}

Merge two objects:

let a={x:1,y:2};
let b={z:3};
let ab={...a,...b};
console.log(ab); // {x:1,y:2,z:3}

5. Function extension

◼️ Default parameters for functions

ES6 provides default values ​​for parameters. This parameter is initialized when the function is defined, so that when the parameter is not passed

Used when passing in.

◼️ Arrow functions

In ES6, a concise function writing method is provided, which we call "arrow function".

Writing method: function name=(parameter)=>{……} When there is only one expression in the function body, {} and return can be omitted

When there is only one formal parameter in the function body, () can be omitted.

Features: this in the arrow function always points to the function closest to this when the arrow function is defined, if there is no closest

The nearest function points to window.

6. Template strings

Identified by a pair of backticks (`), it can be used as a normal string, or it can be used to define a multi-line string, or

Embed variables, js expressions or functions in strings, variables, js expressions or functions need to be written in ${ }.

var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
// return "Hello Bob, how are you today?"

7. for...of loop

var arr=["小林","小吴","小佳"];
for(var v of arr){
console.log(v);
}
//小林 //小吴 //小佳

8. The Class class has constructor, extends, and super, which is essentially syntactic sugar (it has no effect on the language function, but it is more convenient for programmers to use).

class Artist {
    constructor(name) {
        this.name = name;
    }

    perform() {
        return this.name + " performs ";
    }
}

class Singer extends Artist {

    constructor(name, song) {
        super.constructor(name);
        this.song = song;
    }

    perform() {
        return super.perform() + "[" + this.song + "]";
    }
}

let james = new Singer("Etta James", "At last");
james instanceof Artist; // true
james instanceof Singer; // true

james.perform(); // "Etta James performs [At last]"

Inheritance of class In ES6, the prototype chain is no longer used to implement inheritance like ES5, but the concept of Class is introduced.

◼️ Advantages of classes written in ES6 compared to ES5:

Different from functions, more specialized (similar to classes in JAVA);

The writing method is simpler, and it is easier to implement class inheritance;

9. Map + Set + WeakMap + WeakSet

The four types of collections, WeakMap and WeakSet as property key objects will be recycled and released if no other variables are referencing them.

// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;

// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;

//WeakMap
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined

// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });//Because the added object has no other references, it will not be held in the set

10. Math + Number + String + Array + Object APIs

some new APIs

Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false

Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2

"abcde".includes("cd") // true
"abc".repeat(3) // "abcabcabc"

Array.from(document.querySelectorAll('*')) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior

[0, 0, 0].fill(7, 1) // [0,7,7]
[1, 2, 3].find(x => x == 3) // 3
[1, 2, 3].findIndex(x => x == 2) // 1
[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"

Object.assign(Point, { origin: new Point(0,0) })

11. proxies: use proxy (Proxy) to monitor the operation of the object, and then do some corresponding things.

var target = {};
var handler = {
  get: function (receiver, name) {
    return `Hello, ${name}!`;
  }
};

var p = new Proxy(target, handler);
p.world === 'Hello, world!';

可监听的操作: get、set、has、deleteProperty、apply、construct、getOwnPropertyDescriptor、defineProperty、getPrototypeOf、setPrototypeOf、enumerate、ownKeys、preventExtensions、isExtensible。 

12. Symbol: unique name

Symbol is a primitive type. Symbol is generated by calling the symbol function, which accepts an optional name parameter, and the symbol returned by this function is unique.

var key = Symbol("key");
var key2 = Symbol("key");
key == key2  //false

13. Promises: Objects that handle asynchronous operations. After using the Promise object, you can use a chain call to organize the code to make the code more intuitive (similar to jQuery's deferred object).

function fakeAjax(url) {
  return new Promise(function (resolve, reject) {
    // setTimeouts are for effect, typically we would handle XHR
    if (!url) {
      return setTimeout(reject, 1000);
    }
    return setTimeout(resolve, 1000);
  });
}

// no url, promise rejected
fakeAjax().then(function () {
  console.log('success');
},function () {
  console.log('fail');
});

Promise object Promise is a solution for asynchronous programming. It expresses asynchronous operations in the process of synchronous operations, avoiding layers of nested callback functions. If it is to solve asynchronous processing callback hell (that is, the problem of loop nesting) produced.

The Promise constructor takes one parameter and a Promise with two parameters resolve (analysis) and reject (rejection)

callback. In the callback do something (e.g. asynchronously) and if everything is ok call resolve else call

reject。

For the Promise object that has been instantiated, you can call the Promise.then() method, passing resolve and

The reject method acts as a callback.

The then() method receives two parameters: onResolve and onReject, which respectively represent the three states of the Promise when the current Promise object succeeds or fails: Fulfilled is a successful state, Rejected is a failed state, and Pending is neither a Fulfilled nor a Rejected state , which can be understood as the initial state when the Promise object instance is created

14. import and export

In the ES6 standard, JavaScript natively supports modules. This splitting of JS code into small chunks of different functions

Modularization, the codes of different functions are written in different files, and each module only needs to export the public interface part, and then pass

The way of importing through modules can be used in other places.

export is an interface used to export the variables of this module (a file can be understood as a module).

import is used to load another module that contains an export interface in a module.

import and export commands can only be placed at the top of a module, not within a code block.

15. Set data structure

Set is a new data structure provided by ES6, similar to an array. All data is unique and there are no duplicate values. It is itself a constructor. Since the members are all unique and non-repetitive, Setoperations such as deduplication, intersection, union, and complement of arrays can be easily realized.

◼️ Set properties and methods
 

Size () the length of the data

Add() adds a value, returning the Set structure itself.

Delete() deletes a value and returns a Boolean value indicating whether the deletion was successful.

Has() Finds a piece of data and returns a Boolean value.

Clear() clears all members and has no return value.

interface Set {
    add(value): this;
    clear(): void;
    delete(value): boolean;
    forEach(callbackfn: (value, value2, set: Set) => void, thisArg?: any): void;
    has(value): boolean;
    readonly size: number;
}

◼️ Set main application scenarios: array deduplication, intersection, union, and complement.
 

According to Setthe characteristics of , there are many scenarios that can be Setquickly realized. JavaScript Set Practical Scenarios (Arrays: Deduplication, Intersection, Union, Complement)

let arr1 = [1, 2, 3, 4, 5, 6, 7, 4, 3, 2, 1];

// 去重
let newArr = [...new Set(arr1)];
console.log(arr1); // [LOG]: [ 1, 2, 3, 4, 5, 6, 7, 4, 3, 2, 1 ] 
console.log(newArr); // [LOG]: [ 1, 2, 3, 4, 5, 6, 7 ] 
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [3, 4, 5, 6, 7];

let arr1_set = new Set(arr1);
let arr2_set = new Set(arr2);

// 交集
let intersectionArr = [...arr1_set].filter(val => arr2_set.has(val));

console.log(intersectionArr );  // [LOG]: [ 3, 4, 5]

// 并集
let unionArr = [...new Set([...arr1, ...arr2])];
console.log(unionArr );  // [LOG]: [ 1, 2, 3, 4, 5, 6, 7 ] 

// 补集
let complementaryArr = [...arr1_set].filter(val => !arr2_set.has(val));
console.log(complementaryArr );  // [LOG]: [ 1, 2 ] 

15.  Modules

ES6's built-in modules feature draws on the respective strengths of CommonJS and AMD:

(1) It has the characteristics of CommonJS's streamlined syntax, single exports and cyclic dependencies.

(2) Like AMD, it supports asynchronous loading and configurable module loading.

// lib/math.js
export function sum(x, y) {
  return x + y;
}
export var pi = 3.141593;

// app.js
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));

// otherApp.js
import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));

Module Loaders:
// Dynamic loading – ‘System’ is default loader
System.import('lib/math').then(function(m) {
  alert("2π = " + m.sum(m.pi, m.pi));
});

// Directly manipulate module cache
System.get('jquery');
System.set('jquery', Module({$: $})); // WARNING: not yet finalized

Finally, let's look at the difference between ES5 and ES6:

1. Introduction of system library

ES5: You need to use require to import the React package first, become an object, and then make a real reference;

ES6: You can use the import method to directly implement system library references without creating an additional class library object

2. Export and reference a single class

ES5: To export a class to other modules, it is generally implemented through module.exports. When referencing, it is still obtained through the require method;

ES6: You can use export default to achieve the same function, and use the import method to achieve import

3. Define components

ES5: The definition of component class can be realized by React.createClass

ES6: Just let the component class inherit the React.Component class

4. Component internal definition method

ES5: The form of ###:function() is adopted, and a comma needs to be added at the end of the curly braces of the method;

ES6: The [: function] paragraph is omitted, and there is no need to add a comma at the end to achieve separation.

5. Define the attribute type and default attribute of the component

ES5: property types and default properties are implemented through the propTypes member and the getDefaultProps method respectively (these two methods should have fixed names);

ES6: Uniformly use static members to achieve.

6. Initialize STATE

ES5: The method of initializing state is fixed getInitialState;

ES6: The first one is to directly construct the state function; the second one is equivalent to the method rewriting in OC, rewriting the constructor method

Guess you like

Origin blog.csdn.net/sunyctf/article/details/125970107