Transferred from:http://www.cnblogs.com/Wayou/p/es6_new_features.html
ES6 learning can be consulted:http://es6.ruanyifeng.com/
This article is based on lukehoban/Es6features , at the same time refer to a large number of blog material, specifically cited at the end.
ES6 (ECMAScript 6) is the upcoming new version of the JavaScript language standard, codenamed Harmony (harmonious meaning, obviously did not keep pace with our country, we have entered the Chinese Dream version). The last standard was enacted in 2009 ES5. The current standardization of ES6 is underway and is expected to be released in December 14 in an officially finalized version. But most of the standards are already in place, and the browser support for ES6 is also being implemented. To see support for ES6, click here.
If you want to run the ES6 code now, you can use google/traceur-compiler to translate the code. Click here to access the Traceur-compiler online version to edit the ES6 code and view the converted results, and the results of the code run will be displayed in the console.
In addition, about Google Traceur, the industry's great God Addy Osmani use the former to write a chrome plugin ES6 TEPL, after installation can also be ES6 test.
Of course, not all ES6 new features have been implemented, so the methods above can be tested for the most part, and some of them cannot be tested.
Although ES6 has not really released, but has been useful ES6 rewrite the program, a variety of ES789 on the proposal has begun, which you 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 left behind, the following to appreciate the next ES6 in the new features, a generation of JS style.
Arrow operator
If you have C # or Java, you must 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, and the right side is the action to be taken and the value returned inputs=>outputs.
We know that the callback in JS is often the case, and the general callback in the form of anonymous functions, each time need to write a function, is very cumbersome. When the arrow operator is introduced, the callback can be easily written. Take a look at the example below.
var array = [1, 2, 3];//traditional notation Array.foreach (function (v, I, a) { console.log (v);}); /es6array.foreach (v = > console.log (v));
You can open the article at the beginning of the Traceur online Code translation page to enter code to see the effect.
Support for classes
ES6 added support for classes, introduced the class keyword (in fact, the class in JavaScript has always been reserved word, the purpose is to consider possible in the new version will be used, and now finally come in handy). JS itself is object-oriented, and the class provided in ES6 is actually just a wrapper for JS prototype mode. Now that the native class support is provided, object creation, inheritance is more intuitive, and concepts such as invocation, instantiation, static methods, and constructors of the parent method are more visualized.
The following code shows the use of classes in ES6. Again, you can paste the code into traceur to see the results of your run.
Class definition 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) { ///Call the parent class constructor directly 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 literals
Object literals are enhanced, the wording is more concise and flexible, and there are more things to do when defining objects. Specific performance in:
- You can define prototypes in object literals
- Definition methods can be used without the function keyword
- Calling the parent class method directly
In this way, object literals are more consistent with the class concepts mentioned earlier, and are easier to write when writing object-oriented JavaScript.
Create object by object literal var human = { Breathe () { console.log (' breathing ... ');} }; var worker = { __proto__: Human,//Set the prototype for 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 ... '
String templates
String templates are relatively straightforward to understand. ES6 allows the use of anti-quotes ' to create a string inside a string that can contain a variable ${vraible} that is enclosed by a dollar sign and curly braces. If you have used a back-end strongly typed language such as C #, you should not be unfamiliar with this feature.
Generate a random number var num=math.random ();//output this number to Consoleconsole.log (' Your num is ${num} ');
Deconstruction
automatically resolves values in an array or object. For example, if a function returns multiple values, it is common practice to return an object that returns each value as a property of the object. In ES6, however, by using the Deconstruction feature, you can return an array directly, and the values in the array are automatically parsed into the corresponding variable that receives the value.
var [x,y]=getval (),//Deconstruction of function return value [name,,age]=[' wayou ', ' Male ', ' secrect '];//array deconstructed function getval () {
Parameter default value, indeterminate parameter, extension parameter default parameter value
It is now possible to specify the default value of a parameter when defining a function, rather than using logic or operators to achieve the purpose as before.
function SayHello (name) {//traditional way to specify 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 Dudesayhello (' wayou ');//output: Hello WayousayHello2 ();//output: Hello DudesayHello2 (' wayou ');// Output: Hello wayou
Indeterminate parameters
An indeterminate parameter is an unnamed parameter that receives an indefinite number of parameters at the same time using a named parameter in the function. This is just a syntactic sugar, which we can do with the arguments variable in the previous JavaScript code. The format of an indeterminate parameter is a three period followed by a variable name that represents all the indeterminate arguments. For example, in this case, ... x represents the arguments for all incoming add functions.
Add all the arguments to the function functions (... x) {return x.reduce ((m,n) =>m+n);} Pass any number of arguments console.log (add);//output: 6console.log (Add (1,2,3,4,5));//output: 15
Expansion parameters
The extension parameter is another form of syntactic sugar that allows you to pass an array or array of classes directly as a function parameter without using apply.
Let with the const keyword
You can think of let as Var, except that the variable it defines is scoped to a specific range to be used, and leaving the range is invalid. Const is intuitive to define constants, which are variables that cannot be changed.
for (Let i=0;i<2;i++) Console.log (i);//output: 0,1console.log (i);//output: Undefined, error in strict mode
For value traversal
We all know that for-in loops are used to iterate over an array, an array of classes, or an object, and the newly introduced for-for loop function in ES6 is similar, unlike each loop it provides instead of an ordinal but a value.
var somearray = ["A", "B", "C"]; For (V of Somearray) { console.log (v);//Output A,b,c}
Note that this feature is not implemented by Google Traceur, so it is not possible to simulate debugging, and some of the features below
Iterator, generator
This part of the content is a little jerky, details can be found here. Here are some basic concepts.
- Iterator: It is an object that has a next method that returns an object {Done,value}, which contains two properties, a Boolean type of done and a value containing any values
- Iterable: This is an object that has a obj[@ @iterator] method, which 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: The constructor of the generator. The yield keyword can be used within this function. Where yield occurs, the value can be passed to the outside world via the next or throw method of the generator. The generator function is declared by function*.
- Yield keyword: it can pause the execution of a function, and then can go into the function to continue execution
Module
In the ES6 standard, JavaScript native support module. This modular concept of splitting JS code into different functions is popular in a number of tripartite specifications, such as COMMONJS and AMD models.
The different functions of the code are written in separate files, each module only need to export the common interface section, and then through the module's import can be used elsewhere. The following example is from Tutsplus:
Point.jsmodule "Point" {Export class ' point ' { constructor (x, y) {public x = x; Public y = y;}}} The module referenced by the myapp.js//declaration is "/point.js";//It can be seen that, although the referenced module is declared, it can be imported by specifying the required portion of the import point from the "point"; var origin = new Point (0, 0); Console.log (origin);
Map,set and Weakmap,weakset
These are the newly added collection types, providing a more convenient way to get property values, instead of using hasOwnProperty to check whether a property belongs to the prototype chain or the current object as before. At the same time, there is a special Get,set method for adding and fetching property values.
The code below comes from Es6feature
Setsvar s = new Set (), S.add ("Hello"). Add ("Goodbye"). Add ("Hello"); s.size = = = 2;s.has ("hello") = = = true;//Mapsvar m = NE W Map (); M.set ("Hello", M.set); M.get (s) = = 34;
Sometimes we use objects as keys to hold property values, and ordinary collection types, such as simple objects, prevent the garbage collector from recycling objects that exist as property keys, and there is a risk of memory leaks. And the Weakmap,weakset is more secure, these objects as property keys if there are no other variables referencing them, it will be released by recycling, specifically, see the following example.
Body code from Es6feature
Weak mapsvar wm = new Weakmap () Wm.set (s, {extra:42}); wm.size = = undefined//Weak setsvar ws = new WeakSet (); Ws.add ({data:42});//Because this temporary object added to WS does not have other variables referencing it, WS does not save its value, which means that this addition does not actually mean
Proxies
Proxy can listen to what is happening on the object and perform some corresponding actions 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, PR Operty, value) { Console.log (property, ' was changed to ', value); Receiver[property] = value; }};/ /create agent for Listening engineer = proxy (engineer, Interceptor);//Make some changes to trigger proxy engineer.salary = 60;//Console output: Salary is changed to 60
The above code I have annotated, here further explanation. For handlers, the handlers are called after a corresponding event has occurred on the object being listened to, and in the example above we set the handler function of the set, which means that if the property of the object we are listening to is changed, that is set, the handler is called, At the same time, it is possible to know which property was changed by the parameter and what value to change.
Symbols
We know that an object is actually a collection of key-value pairs, whereas a key is usually a string. Now, in addition to the string, we can also use the value of symbol as the object's key. Symbol is a basic type, like a number, a string, and a Boolean, which is not an object. The symbol is generated by calling the symbol function, which receives an optional name parameter, and the symbol returned by the function is unique. You can then use this return value as the key for the object. Symbol can also be used to create private properties that cannot be directly accessed by the value of a property that is made a key by symbol.
The following example comes from Es6features
(function () { //create symbol var key = symbol ("key"); function MyClass (privatedata) { This[key] = privatedata; } Myclass.prototype = { dostuff:function () { ... } }}}) var c = new MyClass ("Hello") c["key"] = = = undefined//Cannot access the property because it is private
Math,number,string,object's new API
A number of new APIs have been added to math,number,string and object. The following code is also from Es6features, which provides a simple demonstration of these new APIs.
Number.EPSILONNumber.isInteger (Infinity)//Falsenumber.isnan ("NaN")//Falsemath.acosh (3)// 1.762747174039086math.hypot (3, 4)//5math.imul (Math.pow (2, +)-1, Math.pow (2,)-2)//2 "ABCDE". Contains ("CD")//TR UE "ABC". Repeat (3)//"ABCABCABC" Array.from (Document.queryselectorall (' * '))//Returns a real arrayarray.of (1, 2, 3)//Si Milar to New Array (...), but without special One-arg behavior[0, 0, 0].fill (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.assign (point, {origin:new point (0,0)})
Promises
Promises is a pattern for handling asynchronous operations, previously implemented in many third-party libraries, such as jquery's deferred objects. When you initiate an asynchronous request and bind the. when (),. Do () event handlers, you are actually applying promise mode.
Create Promisevar Promise = new Promise (function (resolve, reject) { //perform some asynchronous or time-consuming operations if (/* If successful */) { Resolve ("St Uff worked! "); } else { reject ("It broke");} ); /bind handler Promise.then (Result) {//promise succeeds then executes console.log here (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.
ES6 new features Overview