ECMASCRIPT6 Quick Start Introduction _ Basic Knowledge

Source: Internet
Author: User
Tags constant garbage collection generator inheritance new set setinterval

Brief introduction

ECMAScript 6 is the next standard for JavaScript, and is in the midst of rapid development, ECMAScript 6, which allows JavaScript to be used to write automated generators (code generator) for complex applications, functions libraries, and code. The latest browsers have partially supported the syntax of ECMAScript 6, and ECMAScript 6 is currently the industry standard, and its popularity is much faster than ES5, mainly because of the rapid support of modern browsers for ES6, especially the Chrome and Firefox browsers, which have been Hold ES6 most of the characteristics.

1. Let, const, and block scopes

Let allows the creation of block-level scopes, and ES6 recommends that you define a variable in a function rather than Var:

var a = 2;
{Let
 a = 3;
 Console.log (a); 3
}
Console.log (a);//2

Another variable declared in a block-level scope that is valid is the const, which declares a constant. In ES6, a const-declared constant is similar to a pointer, which points to a reference, meaning that the "constant" is not immutable, such as:

{
 Const ARR = [5,6];
 Arr.push (7);
 Console.log (ARR); [5,6,7]
 ARR = ten;//TypeError
}

There are a few points to note:

Let keyword declaration variable does not have variable elevation (hoisting) attribute

The Let and const declarations are valid only in the nearest block (curly braces)

When using constant const declarations, use uppercase variables, such as: capital_casing

Const must be assigned when declaring

2. Arrows function (arrow functions)

In ES6, the arrow function is a shorthand form of a function, using parentheses to wrap the argument, following a =>, followed by a function body:

var getprice = function () {return
 4.55;
};
 
Implementation with Arrow Function
var getprice = () => 4.55;

Note that the GetPrice arrow function above pest uses a compact function body that does not require a reture statement, and the following chestnut uses the normal function body:

Let arr = [' Apple ', ' banana ', ' orange '];
 
Let breakfast = Arr.map (fruit => {return
 fruit + ' s ';
});
 
Console.log (breakfast); Apples bananas Oranges

Of course, the arrow function does more than just make the code concise, and this is always bound to point to the object itself. You can look at several chestnuts below:

function person () {
 this.age = 0;
 
 SetInterval (function growup () {
 //in non-strict mode, this of the growup () function points to the Window object
 this.age++;
 }, 1000);
var person = new person ();

We often need to use a variable to save this and then refer to it in the Growup function:

function person () {
 var self = this;
 self.age = 0;

 SetInterval (function growup () {
 self.age++;
 }, 1000);
}

and using the arrow function saves the hassle:

function person () {
 this.age = 0;
 
 SetInterval (() => {
 //|this| point to Person object
 this.age++;
 }, 1000)
;
 
var person = new person ();

3. function parameter Default value

ES6 allows you to set default values for function parameters:

Let Getfinalprice = (price, tax=0.7) => price + price * TAX;
Getfinalprice (500); 850

4. Spread/rest operator

The spread/rest operator refers to ..., specifically spread or Rest needs to look at context.

When used in an iterator, it is a spread operator:

function foo (x,y,z) {
 console.log (x,y,z);
}
 
Let arr = [1,2,3];
Foo (... arr); 1 2 3

When used for a function pass, is a Rest operator:

function foo (... args) {
 console.log (args);
}
Foo (1, 2, 3, 4, 5); [1, 2, 3, 4, 5]

5. Object lexical extension

ES6 allows you to declare the use of shorthand syntax for object literals to initialize the method of defining property variables and functions, and to allow calculation operations in object properties:

function Getcar (make, model, value) {return
 {
 //abbreviated variable make
 ,///equivalent to Make:make
 model,//equivalent to model:model< C5/>value,//equivalent to Value:value
 
 //property You can use an expression to evaluate
 a value [' Make ' + make]: true,///
 
 ignore the ' function ' keyword shorthand object function
 Deprecia Te () {
 This.value-= 2500
 ;
 
}} Let car = Getcar (' Barret ', ' Lee ', 40000);
 
Output: {
//Make: ' Barret ',//
model: ' Lee ',//
value:40000,
//Makebarret:true,
// Depreciate:function ()
///}

6. Binary and octal literal volume

ES6 supports the literal amount of binary and octal literals, which can be converted to binary values by adding 0o or 0O before the number:

Let ovalue = 0o10;
Console.log (Ovalue); 8 let
 
bvalue = 0B10//binary using ' 0b ' or ' 0B '
console.log (bvalue);//2

7. Object and Array Deconstruction

Deconstruction avoids the creation of intermediate variables when an object is assigned to a value:

function foo () {return
 [1,2,3];
}
Let arr = foo (); [1,2,3] Let
 
[A, B, c] = foo ();
Console.log (A, B, c); 1 2 3
 
function bar () {return
 {
 x:4,
 y:5,
 z:6
 };
}
Let {x:x, y:y, z:z} = Bar ();
Console.log (x, y, z); 4 5 6

8. Object Super Class

ES6 allows the Super method to be used in objects:

var parent = {
 foo () {
 console.log ("Hello from the parent");
 }
 
var child = {
 foo () {
 super.foo ();
 Console.log ("Hello from the Child");
 }
 
Object.setprototypeof (child, parent);
Child.foo (); Hello from the Parent
  //Hello to the child

9. Template syntax and separator

In ES6, there is a very concise way to assemble a bunch of strings and variables.

${.} used to render a variable
' As a separator

Let user = ' Barret ';
Console.log (' Hi ${user}! '); Hi barret!

For...of VS for...in

For...of is used to traverse an iterator, such as the array:

Let nicknames = [' di ', ' Boo ', ' Punkeye '];
Nicknames.size = 3;
For (let nickname of nicknames) {
 console.log (nickname);
}
Result:di, Boo, Punkeye.

For...in is used to traverse an attribute in an object:

Let nicknames = [' di ', ' Boo ', ' Punkeye '];
Nicknames.size = 3;
For (let nickname in nicknames) {
 console.log (nickname);
}
result:0, 1, 2, size

Map and Weakmap

Two new data structure sets in ES6: Map and Weakmap. In fact, each object can be viewed as a map.

An object is composed of multiple key-val pairs, in which any type can be the key of an object, such as:

var mymap = new Map ();
 
var keystring = "A string",
 keyobj = {},
 Keyfunc = function () {};
 
Set Value
mymap.set (keystring, "value is associated with ' a string");
Mymap.set (Keyobj, "Value and Keyobj association");
Mymap.set (Keyfunc, "Value and Keyfunc association");
 
Mymap.size; 3
 
//Get value
mymap.get (keystring);//"Value and ' A String ' association"
Mymap.get (keyobj);//"Value and Keyobj Association"
Mymap.get (Keyfunc); "Value is associated with Keyfunc"

Weakmap

Weakmap is a Map, except that all of its keys are weak references, meaning that things in weakmap are not considered in garbage collection, and use it without worrying about memory leaks.

Another point to note is that all key weakmap must be objects. It has only four methods Delete (key), has (key), get (key) and set (Key, Val):

Let w = new Weakmap ();
W.set (' A ', ' B '); 
Uncaught typeerror:invalid value used as weak map key
 
var O1 = {},
 O2 = function () {},
 O3 = window;
 
W.set (O1, Panax Notoginseng);
W.set (O2, "Azerty");
W.set (O3, undefined);
 
W.get (O3); Undefined, because is the set value
 
W.has (O1);//True
W.delete (O1);
W.has (O1); False

Set and Weakset

A set object is a set of values that are not duplicates, and duplicate values are ignored, and value types can be of the original type and reference type:

Let MySet = new Set ([1, 1, 2, 2, 3, 3]);
Myset.size; 3
Myset.has (1);//True
myset.add (' strings ');
Myset.add ({a:1, b:2});

You can traverse the Set object through ForEach and For...of:

Myset.foreach (item) => {
 console.log (item);
 1
 //2
 //3
 //' strings '/
 //Object {a:1, b:2}
})
 
; For (let value of MySet) {
 console.log (value);
 1
 //2
 //3
 //' strings '///
 Object {a:1, b:2}
}

The Set also has the delete () and clear () methods.

Weakset

Similar to the Weakmap,weakset object allows you to save a weak reference to an object in a collection that only occurs once in Weakset:

var ws = new Weakset ();
var obj = {};
var foo = {};
 
Ws.add (window);
Ws.add (obj);
 
Ws.has (window);  True
Ws.has (foo);//False, Foo did not add success
 
ws.delete (window);//Remove Window Object
ws.has (window) from union;//False, Window object has been deleted

13. Class

There is a class syntax in ES6. It is worth noting that the class here is not a new object inheritance model, it is just a prototype chain of syntactic sugar expression.

Methods and properties that define constructors using static keywords in a function:

Class Task {
 constructor () {
 console.log ("Task instantiated!");
 }
 
 Showid () {
 console.log ();
 }
 
 Static Loadall () {
 Console.log ("Loading All Tasks ...");
 }
 
Console.log (typeof Task); function let
task = new task ();//"Task instantiated!"
Task.showid ();
Task.loadall ()//"Loading All Tasks ..."

Inheritance and superset in a class:

Class Car {
 constructor () {
 console.log ("Creating a new Car");
 }
 
Class Porsche extends Car {
 constructor () {
 super ();
 Console.log ("Creating Porsche");
 }
 
Let C = new Porsche ();
Creating a new car
//creating Porsche

Extends allows a subclass to inherit the parent class, it should be noted that the super () function is required in the constructor function of subclasses.

Of course, you can also invoke the parent class method in the subclass method, such as Super.parentmethodname ().

Read more about the class here.

There are a few noteworthy points to note:

The declaration of a class is not elevated (hoisting), if you want to use a class, you must define it before you use it, or you will throw a referenceerror error
Defining functions in a class does not require the use of function keywords

Symbol

Symbol is a new data type whose value is unique and immutable. Symbol is proposed in ES6 to generate a unique identifier, but you cannot access this identifier:

var sym = Symbol ("Some optional description");
Console.log (typeof sym); Symbol

Note that the new operator cannot be used before Symbol here.

If it is used as a property of an object, then this property is not enumerable:

var o = {
 val:10,
 [Symbol ("random")]: "I ' m a Symbol",
};
 
Console.log (Object.getownpropertynames (o)); Val

If you want to get the object symbol property, you need to use Object.getownpropertysymbols (O).

15. Iterator (iterators)

An iterator allows you to access one element of a data collection at a time, and the iterator exits when the pointer points to the last element of the data set. It provides the next () function to traverse a sequence that returns an object that contains the done and the value properties.

In ES6, you can set the default traversal for an object by Symbol.iterator, and whenever the object needs to be traversed, the @ @iterator method that executes it can return an iterator to get the value.

An array by default is an iterator:

var arr = [11,12,13];
var ITR = Arr[symbol.iterator] ();
 
Itr.next (); {value:11, done:false}
itr.next ();//{value:12, done:false}
itr.next ();//{value:13, Done:false}< C5/>itr.next (); {value:undefined, done:true}

You can customize an iterator for an object by [Symbol.iterator] ().

Generators

The generator function is a new feature of the ES6 that allows a function to return a traversal object that generates multiple values.

In use you will see * syntax and a new keyword yield:

function *infinitenumbers () {
 var n = 1;
 while (true) {
 yield n++
 }
}
 
var numbers = Infinitenumbers (); Returns an Iterable object
 
numbers.next ();//{value:1, done:false}
numbers.next ();//{value:2, Done: False}
Numbers.next ();//{value:3, Done:false}

Each time the yield is executed, the returned value becomes the next value of the iterator.

Promises

ES6 has native support for Promise, a Promise is an object that waits to be executed asynchronously, and its state becomes resolved or rejected when it is executed.

var p = new Promise (function (resolve, reject) { 
 if (/* condition */) {
 //fulfilled successfully resolve
 (/* VA Lue * *); 
 } else {
 //error, rejected
 reject (/* reason/); 
 }
);

Every Promise has a. Then method, which takes two parameters, the first is a callback that handles the resolved state, and a callback that handles the rejected state:

P.then ((val) => Console.log ("Promise resolved", Val),
 (Err) => Console.log ("Promise rejected", err));

The above is for everyone to organize the ECMASCRIPT6 Quick start of the brief, need friends can learn reference.

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.