The latest standard Es6_javascript tips for learning JavaScript with me

Source: Internet
Author: User
Tags export class generator instance method new set pow

Although ES6 has not really released, but has been useful ES6 rewrite the program, various ES789 proposals have begun, which you dare to believe. The tide is not what I wait for the masses to catch up with.

Although the trend is too fast, but we continue to learn the pace, will not be lost by the trend, below to enjoy the new characteristics of the next ES6, a generation of JS style.

Arrow operator

If you can C # or Java, you definitely know the lambda expression, the new arrow operator in ES6 =>. It simplifies the writing of functions. The left side of the operator is the input parameter, while the right-hand side is the operation performed and the returned value inputs=>outputs.

We know that in JS callback is a regular thing, and the general callback in the form of anonymous functions, each time need to write a function, very cumbersome. The callback can be written easily when the arrow operator is introduced. Take a look at the example below.

var array = [1, 2, 3];
Traditional writing
Array.foreach (function (v, I, a) {
 console.log (v);
});
ES6
Array.foreach (v = > console.log (v));

You can view the effect by opening the Traceur online Code translation page entry code mentioned at the beginning of the article.

Support for classes

ES6 added support for classes, introducing the Class keyword (in fact, the class is always reserved in JavaScript for the purpose of taking into account the possibility that it will be used in a later version of it, and is now finally useful). JS itself is object-oriented, the class provided in the ES6 is actually only the JS prototype packaging. With native class support now available, object creation, inheritance is more intuitive and concepts such as invocation of parent methods, instantiation, static methods, and constructors are more visualized.

The following code shows the use of classes in ES6. Again, you can post the code to traceur yourself to see the results of the run.

Class
Animal {
 //es6 New constructor
 Constructor (name) {
 this.name = name;
 }
 Instance method
 Sayname () {
 console.log (' My name is ' +this.name);
 }
}
Class
programmer extends Animal {
 constructor (name) {
 //directly invokes the parent class constructor to initialize
 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 ()//Output ' My name is Wayou '
wayou.program ();//Output ' I ' m Coding ... '
 

Enhanced object literal

The object literal is enhanced, the writing is more concise and flexible, and there are more things to do when defining objects. The specific performance in:

    • You can define a prototype in the literal volume of an object
    • You can define methods without the function keyword
    • Calling the parent class method directly

As a result, object literals are more consistent with the class concepts mentioned earlier, and are easier to write object-oriented JavaScript.

Object literal is created by object
var human = {
 Breathe () {
 console.log (' breathing ... ');
 }
;
var worker = {
 __proto__: Human,//Set this object's prototype to human, equivalent to inheriting human company
 : ' Freelancer ',
 work () {
 Console.log (' working ... ');
 }
;
Human.breathe ()//output ' breathing ... '
//Call inherited Breathe Method
worker.breathe ()//output ' breathing ... '

String templates

The string template is relatively straightforward. ES6 allows the use of inverted quotes ' to create a string that can contain a variable ${vraible} enclosed by a dollar sign plus curly braces. If you've ever used a back-end strongly typed language like C #, you shouldn't be unfamiliar with this feature.

Generate a random number of
var num=math.random ();
Output this number to the console
console.log (' Your num is ${num} ');

Deconstruction

automatically resolves the values in an array or object. For example, if a function returns more than one value, the general practice is to return an object and return each value as the property of the object. In ES6, however, by using the feature of deconstruction, you can return an array directly, and then the values in the array are automatically parsed into the corresponding variables that receive the value.

X,y]=getval [
 name,,age]=[' wayou ', ' Male ', ' secrect '];//array destructor 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 

Parameter default value, indefinite parameter, expand parameter

1. Default parameter values

You can now specify the default value of the parameter when you define the function, instead of using the logic or the operator to achieve the goal as before.

function SayHello (name) {
 //traditional way of specifying default parameters
 var name=name| | ' Dude ';
 Console.log (' Hello ' +name);
}
Use ES6 default parameter
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

2. Indefinite parameters

An indeterminate parameter is an unnamed parameter that receives an indefinite number of arguments in a function using named parameters. This is just a syntactic candy, and we can do that by arguments variables in the previous JavaScript code. Indefinite parameters are formatted with three periods followed by variable names that represent all indeterminate parameters. For example, in the following example, ... x represents all parameters that are passed in to the Add function.

function
Add (... x) {return
 x.reduce (m,n) =>m+n) with
all parameters added;
Pass any number of parameters
Console.log (Add (1,2,3));//output: 6
console.log (Add (1,2,3,4,5));//output: 15 

3, expand the parameters

The extension argument is another form of syntactic sugar that allows you to pass an array or a class array directly as a function parameter without having to apply.

var people=[' wayou ', ' John ', ' Sherlock '];
The SayHello function would have received three separate parameters of the Simon, the human two and the human three
function SayHello (people1,people2,people3) {
 console.log (' Hello ${ People1},${people2},${people3} ');
But we pass an array in the form of an extension parameter, which maps well to each individual parameter
SayHello (... people);//output: Hello wayou,john,sherlock 

//And in the past, If you need to pass an array as a parameter, we need to use the Apply method of the function
sayhello.apply (null,people);/output: Hello wayou,john,sherlock 

Let and const keywords

Let can be viewed as VAR, except that its defined variables are limited to a certain range to be used, and leaving this range is not valid. The const is intuitive and is used to define constants, that is, variables that 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 value traversal

We all know that for-in loops are used to traverse an array, an array of classes, or an object, the newly introduced for of the loop function in ES6 is similar, unlike each loop it provides a value instead of an ordinal.

var somearray = ["A", "B", "C"];
 
for (v Somearray) {
 console.log (v);//Output A,b,c
}

Note that this feature is not implemented by Google Traceur, so it cannot simulate debugging, and so are some of the following features

Iterator, generator

This part of the content is a bit jerky, see here for details. Here are some basic concepts.

    • Iterator: It's an object that has a next method that returns an object {Done,value}, which contains two attributes, a boolean-type done and value containing any value
    • Iterable: This is an object that has a obj[@ @iterator] method that returns a iterator
    • Generator: It is a special kind of iterator. The inverse next method can receive a parameter and the return value depends on its constructor (generator function). Generator also has a throw method
    • Generator function: That is, the generator constructor. You can use the yield keyword within this function. Where the yield appears, you can pass the value to the outside by the generator next or throw method. The generator function is declared by function*.
    • Yield keyword: It can suspend the execution of a function, and then go back into function to continue execution

Module

In the ES6 standard, JavaScript native supports module. The concept of modularity in a small block that divides JS code into different functions is prevalent in a number of tripartite specifications, such as the COMMONJS and AMD models.

The different functions of the code are written in different files, the modules only need to export the common interface part, and then through the import of modules can be used elsewhere. The following examples come from Tutsplus:

Point.js
Module "point" {
 Export class Point {
 constructor (x, y) {public
  x = x;
  Public y = y;
 }
 }
 
Myapp.js
//Declares the referenced module
"/point.js";
As can be seen here, although the referenced module is declared, it is possible to import the import point from "point" by specifying the desired part
;
 
var origin = new Point (0, 0);
Console.log (origin);

Map,set and Weakmap,weakset

These are the newly added collection types, which provide a more convenient way to get property values, without using hasOwnProperty as before to check whether a property belongs to the prototype chain or the current object. At the same time, there is a special Get,set method when the attribute value is added and obtained.

The code below comes from Es6feature

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",);
M.set (S,);
M.get (s) = = 34;

Sometimes we use objects as keys for an object to hold attribute values, and common collection types, such as simple objects, prevent the garbage collector from reclaiming objects that exist as property keys, and are at risk of causing memory leaks. While Weakmap,weakset is more secure, these objects as property keys are recycled if they are not referenced by other variables, as shown in the following example.

Body code from Es6feature

Weak Maps
var wm = new Weakmap ();
Wm.set (S, {extra:42});
Wm.size = = undefined

//Weak Sets
var ws = new Weakset ();
Ws.add ({data:42});//Because this temporary object that is added to WS has no other variables to reference it, WS does not save its value, which means that this addition is not meant to be

Proxies

A proxy can listen to what's happening on the object and perform some action after these things happen. All of a sudden, we have a strong ability to track an object, but also useful in data binding.

The following examples are borrowed from here.

Defines the target object being listened to
var engineer = {name: ' Joe sixpack ', salary:50};
Define Handler
var interceptor = {
 Set:function (receiver, property, value) {
 Console.log 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

I have added the code above to explain it further. For handlers, after a corresponding event occurs on the object being listened to, the method inside the handler is invoked, and in the example above we set the handler function of the set, indicating that if the property of the object we are listening to is changed, that is set, the handler will be invoked. At the same time, it is possible to know which property is changed and what value to change by using parameters.

Symbols

We know that the object is actually a collection of key-value pairs, and the key is usually a string. And now, in addition to strings, we can use the value of symbol as the key to the object. Symbol is a basic type, like a number, a string, and a Boolean, which is not an object. Symbol is generated by calling the symbol function, which receives an optional name argument, which returns the symbol that is unique. You can then use this return value as the object's key. Symbol can also be used to create private properties that cannot be accessed directly from the property value as a key by symbol.

The following examples are from Es6features

(function () {

 //create 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//Cannot access this property because it is private

New API for Math,number,string,object

A number of new APIs have been added to math,number,string and object. The following code also comes from Es6features, which is a simple demonstration of these 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)-1, Math.pow (2,)-2)//2

"ABCDE". Conta INS ("CDs")//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
[0, 0, behavior (7, 1)/ /[0,7,7]
[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.assi GN (Point, {origin:new point (0,0)})

Promises

Promises is a pattern for handling asynchronous operations, which were previously implemented in many tripartite libraries, such as the deferred object of jquery. When you initiate an asynchronous request and bind the. When (), the. Done () and other event handlers are actually applying the promise mode.

Create Promise
var promise = new Promise (function (resolve, reject) {
 //perform some asynchronous or time-consuming operations if (////
 if successful) {
 resolv E ("Stuff worked!");
 } else {
 reject (Error ("It broke");
 }
)
; Binding handler
Promise.then (function (result) {
 //promise successful words will execute here
 console.log (result);//"Stuff worked!"
} , function (err) {
 //promise failure will execute here
 console.log (ERR);//Error: "It Broke"
});

Summary is a sentence, the difference between the front and back is getting smaller, this article is based on Lukehoban/es6features, while referring to a large number of blog information, small knitting to do so much homework is to help you better understand the latest JavaScript standards ECMAScript 6, hope to be helpful to everybody's study.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.