Arrow operator
It simplifies function writing. Inputs=>outputs; Inputs=> Inputs; Inputs=> Inputs; Inputs=>outputs We know that callback is a common thing in JS, and most callbacks are in the form of anonymous functions, so we need to write a function every time, which is tedious. Callbacks can be written easily with the introduction of the arrow operator. Take a look at the following example.
If there is more than one parameter, use curly braces (). If there is more than one function statement, use curly braces {}. The arrow function’s this refers to the this object at definition, not execution
var array = [1, 2, 3];
// The traditional way
array.forEach(function(v, i, a) {
console.log(v);
});
//ES6
array.forEach(v = > console.log(v));
Copy the code
Let and const
Let declarations of variables only work in block-level scopes, and are suitable for use in for loops without variable promotion. In the same code block, cannot repeatedly declare the same variable, cannot repeatedly declare the parameters of the function.
Const is also used to declare a constant and must be assigned a value, which cannot be modified. Like let, const is only used in block-level scope and cannot be repeatedly declared.
The support of the classes
ES6 added support for classes and introduced the class keyword (which has always been a reserved word in JavaScript, in case it might be used in a later version, but now comes in handy). JS itself is object-oriented, and the classes provided in ES6 are really just wrappers around THE JS prototype pattern. With native class support, object creation and inheritance are much more intuitive, and concepts like superclass method calls, instantiations, static methods, and constructors are much more visualized.
// Class definition
class Animal {
// A new constructor in ES6
constructor(name) {
this.name = name;
}
// Instance method
sayName() {
console.log('My name is '+this.name); }}// Class inheritance
class Programmer extends Animal {
constructor(name) {
// Call the parent constructor directly for initialization
super(name);
}
program() {
console.log("I'm coding..."); }}// Test our class
var animal=new Animal('dummy'),
wayou=new Programmer('wayou');
animal.sayName();// output 'My name is dummy'
wayou.sayName();'My name is wayou'
wayou.program();// Output 'I'm coding... '
Copy the code
Enhanced object literals
Object literals have been enhanced to be more concise and flexible, and more things can be done when defining objects. Specific performance:
You can define a prototype in an object literal and you can call a parent method without using the function keyword so that object literals are more in line with the class concepts mentioned earlier, making it easier to write object-oriented JavaScript.
// Create an object from an object literal
var human = {
breathe() {
console.log('breathing... '); }};var worker = {
__proto__: human, // Set the prototype of this object to human, which is equivalent to inheriting human
company: 'freelancer'.work() {
console.log('working... '); }}; human.breathe();/ / output 'breathing... '
// Call the inherited breathe method
worker.breathe();/ / output 'breathing... '
Copy the code
String template
The string template is relatively straightforward. In ES6, it is possible to create strings using backquotes, which can contain the variable ${vraible} wrapped in dollar signs and curly braces.
// Generate a random number
var num=Math.random();
// Print this number to console
console.log(`your num is ${num}`); Destruct automatically resolves values in arrays or objects. For example, if a function returns multiple values, the conventional approach is to return an object and return each value as an attribute of that object. In ES6, however, with the deconstruction feature, you can return an array directly, and the values in the array are automatically parsed into the corresponding variables that receive the values.var [x,y]=getVal(),// Destruct the return value of the function
[name,,age]=['wayou'.'male'.'secrect'];// Array destruct
function getVal() {
return [ 1.2 ];
}
console.log('x:'+x+', y:'+y);// Output: x:1, y:2
console.log('name:'+name+', age:'+age);// Output: name:wayou, age:secrect
Copy the code
Default Parameter Value
You can now specify default values for parameters when you define functions, rather than using logic or operators as before.function sayHello(name){
// The traditional way to specify default parameters
var name=name||'dude';
console.log('Hello '+name);
}
// Use ES6 default parameters
function sayHello2(name='dude'){
console.log(`Hello ${name}`);
}
sayHello();// Output: Hello dude
sayHello('Wayou');// Output: Hello Wayou
sayHello2();// Output: Hello dude
sayHello2('Wayou');// Output: Hello Wayou
Copy the code
Uncertain parameters
An indefinite parameter is a function that uses named parameters while receiving an indefinite number of unnamed parameters. This is just a syntactic sugar that we could have done with the arguments variable in previous JavaScript code. The format of the indeterminate argument is three periods followed by the variable name representing all the indeterminate arguments. In the following example… X represents all the arguments passed into the add function.
// A function that adds all the arguments
function add(. x){
return x.reduce((m,n) = >m+n);
}
// Pass any number of arguments
console.log(add(1.2.3));// Output: 6
console.log(add(1.2.3.4.5));// Output: 15
Copy the code
Expand the parameters
Extended arguments are another form of syntactic sugar that allows you to pass arrays or arrays of classes directly as arguments to a function without applying.
var people=['Wayou'.'John'.'Sherlock'];
The sayHello function originally takes three separate arguments, man-two and man-three
function sayHello(people1,people2,people3){
console.log(`Hello ${people1}.${people2}.${people3}`);
}
// But we pass an array as extended parameters that map nicely to each individual parametersayHello(... people);// Output: Hello Wayou,John,Sherlock
Before, if we needed to pass arrays as arguments, we would use the apply method of the function
sayHello.apply(null,people);// Output: Hello Wayou,John,Sherlock
letwithconstKeywords can be putletasvar, but the variable defined by it is restricted to a specific range, and outside this range is invalid.constIt is intuitive to define a constant, a variable whose value cannot be changed.for (let i=0; i<2; i++)console.log(i);// output: 0,1
console.log(i);// Output: undefined, error in strict mode
for ofValue traversal is something we all knowfor inLoops are used to iterate over arrays of numbers, class arrays, or objects, new to ES6for ofLoops function similarly, except that each loop provides a value instead of an ordinal number.var someArray = [ "a"."b"."c" ];
for (v of someArray) {
console.log(v);/ / output a, b, c
}
Copy the code
The module
JavaScript natively supports Modules in the ES6 standard. This concept of modularizing JS code into small chunks of different functionality is popular in some tripartite specifications, such as CommonJS and AMD patterns.
Write the code of different functions separately in different files, each module only needs to export the public interface part, and then use it in other places by importing the module.
// point.js
module "point" {
export class Point {
constructor (x, y) { public x = x; public y = y; }}}// myapp.js
// Declare the referenced module
module point from "/point.js";
// As you can see here, even though the referenced module is declared, you can still import by specifying the required parts
import Point from "point";
var origin = new Point(0.0);
console.log(origin);
Copy the code
Map, Set and WeakMap, WeakSet
These are new collection types that provide a more convenient way to get property values instead of using hasOwnProperty to check whether a property belongs to the stereotype chain or to the current object. At the same time, there are special get and set methods when adding and acquiring attribute values.
// Sets
var s = new Set(a); s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") = = =true;
// Maps
var m = new Map(a); m.set("hello".42);
m.set(s, 34);
m.get(s) == 34;
Copy the code
Sometimes objects are used as property keys to store property values. Common collection types such as simple objects prevent the garbage collector from collecting these property keys, causing a risk of memory leaks. While WeakMap and WeakSet are more secure. If there are no other variables referring to them as the object of the attribute key, they will be recycled and released. Specifically, see the following example.
// Weak Maps
var wm = new WeakMap(a); wm.set(s, {extra: 42 });
wm.size === undefined
// Weak Sets
var ws = new WeakSet(a); ws.add({data: 42 });// Since the temporary object added to WS has no other variable reference to it, WS does not save its value, which means that this addition is actually meaningless
Copy the code
Proxy
The Proxy can listen for things to happen to objects and perform actions when those things happen. All of a sudden it gives us great traceability to an object, and it’s also useful for data binding.
// Define the target object to be listened on
var engineer = { name: 'Joe Sixpack'.salary: 50 };
// Define the handler
var interceptor = {
set: function (receiver, property, value) {
console.log(property, 'is changed to', value); receiver[property] = value; }};// Create a proxy to listen
engineer = Proxy(engineer, interceptor);
// Make some changes to trigger the agent
engineer.salary = 60;// Console output: salary is changed to 60
Copy the code
The above code has been commented and explained further here. For a handler, the method in the handler is called after an event has occurred on the object being listened on. In the example above, we set the set handler to indicate that the handler is called if the properties of the object being listened are changed, that is, set. At the same time, the parameters tell you which attribute is being changed and for what value.
Symbols
We know that objects are really collections of key-value pairs, and keys are usually strings. Now, in addition to strings, we can also use the value symbol as the key of the object. Symbol is a basic type. Like numbers, strings, and booles, it is not an object. The Symbol is generated by calling the Symbol function, which accepts an optional name argument. The Symbol returned by the function is unique. You can then use this return value as the object’s key. Symbol can also be used to create private attributes that are not directly accessible to outsiders.
(function() {
/ / create a symbol
var key = Symbol("key");
function MyClass(privateData) {
this[key] = privateData;
}
MyClass.prototype = {
doStuff: function() {...this[key] ...
}
};
})();
var c = new MyClass("hello")
c["key"= = =undefined// The property cannot be accessed because it is private
Copy the code
New APIS for Math, Number, String, Object
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".contains("cd") // true
"abc".repeat(3) // "abcabcabc"
Array.from(document.querySelectorAll(The '*')) // 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) / /,7,7 [0]
[1.2.3].findIndex(x= > x == 2) / / 1
["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)})Copy the code
Promises
Promises are a pattern for handling asynchronous operations, previously implemented in many three-party libraries, such as jQuery’s Deferred object. When you make an asynchronous request and bind event handlers like.when() and.done(), you’re applying the Promise pattern. Promise can be used more reasonably and formally to handle objects that are operated on asynchronously, and it has three states: initialization, operation success, and operation exception. Use example methods: then() and catch() to bind handlers; Class methods are also provided: promise.all () and promise.race ().
- Promise.all() method: Accepts an array as parameter, the elements of which are Promise instance objects. When the state of the instance objects in the parameter is fulfilled, promise.all () will return
- Promise. Race () method: This parameter requirement is the same as the promise.all () method. The difference is that as long as one of the Promise instances in this parameter changes (whether this is a successful pity or an exception rejected), it will return.
/ / create a promise
var promise = new Promise(function(resolve, reject) {
// Perform some asynchronous or time-consuming operations
if ( /* If successful */ ) {
resolve("Stuff worked!");
} else {
reject(Error("It broke")); }});// Bind handler
promise.then(function(result) {
// Promise will be implemented here if it succeeds
console.log(result); // "Stuff worked!"
}, function(err) {
// Promise failures are implemented here
console.log(err); // Error: "It broke"
});
Copy the code