What new common grammars are added to ES6

Posted by roach on Thu, 09 May 2019 13:12:04 +0200

Defined function
Let's start with a basic new feature. In javascript, defining functions requires keyword functions, but in es6, there are more advanced ways to write them. Let's see:

es6 writing:

var human = {
    breathe(name) {   //UnwantedfunctionIt can also be defined. breathe Function.
        console.log(name + ' is breathing...');
    }
};
human.breathe('jarson');   //output 'jarson is breathing...'

Convert to js code:

var human = {
    breathe: function(name) {
        console.log(name + 'is breathing...');
    }
};
human.breathe('jarson');

Create class
We know that javascript is not an object-oriented programming language like java, but an object-based programming language. So in js, we usually use function and prototype to simulate the concept of class.

But now with es6, we can create a class as blatantly as java does:

class Human {
    constructor(name) {
        this.name = name;
    }
    breathe() {
        console.log(this.name + " is breathing");
    }
} 
var man = new Human("jarson");
man.breathe();    //jarson is breathing

The above code is converted to js format:

function Human(name) {
    this.name = name;
    this.breathe = function() {
        console.log(this.name + ' is breathing');
    }
}
var man = new Human('jarson');
man.breathe();    //jarson is breathing

So we see that we can create a class as semantically as java does. In addition, the inheritance of the parent class in js needs to be implemented with prototype. So in es6, what new way to implement class inheritance? Continue to see:

If we want to create a Man class that inherits the Human class above, es6 code:

class Man extends Human {
    constructor(name, sex) {
        super(name);
        this.sex = sex;
    }
    info(){
        console.log(this.name + 'is ' + this.sex);
    }
}
var xx = new Man('jarson', 'boy');
xx.breathe();   //jarson is breathing
xx.info();   //arsonis boy

The code is very simple, without further elaboration, you can use the online tools mentioned in the article to try the effect. Note that super() is the constructor of the parent class.
Modular
In the ES6 standard, javascript natively supports module. The code of different functions is written in different files. Each module only needs to export the common interface part, and then import the module where it needs to be used. Let's continue with examples:

Inline export
Objects in the ES6 module can be exported directly in the declaration that created them, and export can be used countless times in a module.

First look at the module file app.js:

export class Human{
    constructor(name) {
        this.name = name;
    }
    breathe() {
        console.log(this.name + " is breathing");
    } 
}  
export function run(){  
    console.log('i am runing'); 
}
function eat() {
    console.log('i am eating');
}

The module in the example exports two objects: the Human class and the run function. If the eat function is not exported, the module is still private and cannot be used by other files.
Export a set of objects
In addition, in fact, if there are many objects to export, we can export a set of objects uniformly at the end.

Change the app.js file:

class Human{
    constructor(name) {
        this.name = name;
    }
    breathe() {
        console.log(this.name + " is breathing");
    } 
}  
function run(){  
    console.log('i am runing'); 
}
function eat() {
    console.log('i am eating');
}
export {Human, run}; 

This way of writing functions the same as above, and it is clear that at the end of the day, you can clearly see which objects have been exported.

Default export
The keyword default is used when exporting, and the object can be labeled as default object for exporting. The default keyword can only be used once in each module. It can be used for both inline export and a set of object export declarations.

View the syntax for exporting default objects:

... // Create classes, functions, etc.

export default {  //holdHumanClass sum run The function is labeled as ___________defaultObject export.
    Human,  
    run  
}; 

Objectless import
If a module contains some logic to execute and does not export any objects, such objects can also be imported into another module, after which only logic is executed. Such as:

import './module1.js'; 

Import default objects
Export an object using Default export, which will be assigned directly to a reference in the import declaration, as in the example "app".

import app from './module1.js'; 

In the example above, the default. / module1.js file exports only one object; if a set of objects is exported, they should be listed in the import declaration one by one, such as:

import {Human, run} from './app.js'
letandconst

In my opinion, in the new features of es6, it is better to use let instead of var when defining variables, while const is intuitive to define constants, variables that cannot be changed.

for (let i=0;i<2;i++) {
    console.log(i);  //Output: 0,1
}

Arrow function
The new arrow operator => in ES6 simplifies the writing of functions. The left side of the operator is the input parameter, while the right side is the operation performed and the returned value. This way of writing can reduce a lot of code for us. Look at the following example:

let arr = [6, 8, 10, 20, 15, 9];
arr.forEach((item, i) => console.log(item, i));
let newArr = arr.filter((item) => (item<10));
console.log(newArr); //[6, 8, 9];

The above (item, i) is the parameter, and the following console.log(item, i) is the operation logic to return to the function.

The above code is converted to js format:

var arr = [6, 8, 10, 20, 15, 9];
arr.forEach(function(item, i) {
    return console.log(item, i);
});
var newArr = arr.filter(function(item) {
    return (item < 10);
});
console.log(newArr);

String template
ES6 allows the creation of strings with back quotes, which can contain variables ${vraible} wrapped in dollar symbols and brackets. Look at the examples and you will see that:

//Generate a random number
let num = Math.random();
//Output this number to console
console.log(`your num is ${num}`);

deconstruction
If a function wants to return more than one value, the usual practice is to return an object, and each value is returned as an attribute of the object. In ES6, by using the deconstruction feature, an array can be returned directly, and then the values in the array can be automatically parsed into the variables corresponding to the values received. Let's look at an example:

function getVal() {
    return [1, 2];
}
var [x,y] = getVal(); //Deconstruction of Function Return Value
console.log('x:'+x+', y:'+y);   //Output: x:1, y:2 
//Default parameters

It is now possible to specify the default values of parameters when defining functions, instead of using logic or operators to achieve the goal as before.

function sayHello(name){
    var name=name||'tom';   //Traditional way of specifying default parameters
    console.log('Hello '+name);
}
//Using default parameters of ES6
function sayHello2(name='tom'){  //If this parameter is not passed, there will be a default value.
    console.log(`Hello ${name}`);
}
sayHello();//Output: Hello tom
sayHello('jarson');//Output: Hello jarson
sayHello2();//Output: Hello tom
sayHello2('jarson');//Output: Hello jarson

Note: sayHello2(name='tom') here is the equal sign, meaning that if the parameter is not passed, the default value is set instead of assigning the parameter.

Proxy
Proxy can monitor what happens to the object and perform some corresponding actions after these things happen. All of a sudden, we have a strong ability to trace an object, and it is also very useful in data binding.

//Define the target object being monitored
let engineer = { name: 'Joe Sixpack', salary: 50 };
//Define handler
let interceptor = {
    set(receiver, property, value) {
        console.log(property, 'is changed to', value);
        receiver[property] = value;
    }
};
//Create a proxy for listening
engineer = new Proxy(engineer, interceptor);
//Make some changes to trigger the agent
engineer.salary = 70;//Console output: salary is changed to 70

For a handler, the method in the handler is called after the corresponding event occurs on the monitored object.

Topics: Javascript Java Programming Attribute