Learn the Web from scratch ES6 (iv) ES6 Basic Grammar II

Source: Internet
Author: User
Tags iterable

Hello everyone, here is "learn the Web series from scratch" and synchronize updates at the following address ...

  • Github:github.com/daotin/web
  • Public number: The top of the Web front
  • Blog Park: http://www.cnblogs.com/lvonve/
  • csdn:blog.csdn.net/lvonve/

Here I will start with the Web front End 0 Foundation, step-up learning web-related knowledge points, during the period will also share some fun projects. Now let's go to the Web Front end learning Adventure tour!

First, Promise

Promise is an object that represents a future event that will occur (this event is usually an asynchronous operation)

With the Promise object, asynchronous operations can be expressed in a synchronous process, avoiding nested callback functions (commonly called ' callback hell ').

The promise of ES6 is a constructor that is used to generate promise instances.

1, Promise object 3 states
    • pending: Initialize state
    • fullfilled: Success Status
    • rejected: Failed status
2. How to use

1, create a Promise instance object, the parameter is an anonymous function, this anonymous function has two parameters, resolve and Reject,

2, each parameter is a callback function. Then, the function body typically performs asynchronous operations, such as initiating an AJAX request, or turning on a timer.

3. When the asynchronous operation succeeds, call the resolve callback function and call the Reject callback function when the asynchronous operation fails.

4, when initializing the Promise instance object, the state of promise is pending, when the resolve callback function is called, the Promise State is fullfilled, which indicates the success state, and when the reject callback function is called, The status of Promise is rejected, which indicates the failure state;

5, the Promise instance object has a method then, the parameter is two anonymous functions, the first anonymous function handles the condition of the promise State is fullfilled, the second anonymous function handles the condition of promise with rejected;

6, said above, when the asynchronous operation succeeds or fails, will call the resolve and reject functions, in the two callback functions can pass in parameters, this parameter can be directly into the then two anonymous function parameters used. For example, to get Ajax data, you can pass the obtained number as a parameter into the resolve parameter, and then automatically pass this parameter to then's first anonymous function, Reject is the same.

By means of a diagram:

Example:

    let promise = new Promise((resolve, reject) => {      console.log(111);      // 执行异步操作      setTimeout(() => {        console.log(222);        // 执行异步操作成功,此时修改promise的状态fullfilled        resolve("success!");        // 执行异步操作成功,此时修改promise的状态rejected        reject("failed!");      }, 2000);    });    promise.then((data) => { // promise的状态fullfilled的操作      console.log("成功", data);    }, () => { // promise的状态rejected的操作      console.log("失败", data);    });

Note: When executed to resolve ("success!"); Modify the state of the Promise Fullfilled, the back of the Reject ("failed!"); Will not execute. The Console.log ("failed") statement is not printed.

Promise case: Get news content and comment content

    Define a method to request news function Getnews (URL) {//Create a Promise object let promise = new Promise ((Resolve, Reject) =&gt ; {//Initialize promise State to Pending//Start asynchronous task, initiate AJAX request//1. Create an object of the XMLHttpRequest type let request = new XML        HttpRequest (); 4.  Specifies the XHR state Change event handler request.onreadystatechange = function () {if (request.readystate = = = 4) {if (Request.status = = 200)              {Let news = Request.response;            Resolve (news);            } else {reject (' request failed ... ');        }          }        }; Request.responsetype = ' json '; Sets the returned data type//2. Open a connection to a URL request.open ("GET", url); Specify the method of the request, create the link//3. Send a request Request.send () via a link;    Send})//Only return promise can call then method return promise;    }; Call Getnews to get the news content, where one byte is the address of the comment content getnews (' http://localhost:3000/news?id=2 '). Then (News) = {//get to the press        Content Console.log (news); Document.wrITE (Json.stringify (News));        Get the comment address in the news content Console.log (' http://localhost:3000 ' + news.commentsurl);        Gets the news comment content recursively, and returns the Promise object for the chained then method.      Return getnews (' http://localhost:3000 ' + news.commentsurl);      }, (Error) = {alert (error);        }). Then ((comments) = {//Then method can be chained programming console.log (comments); Print the comment part of the news in JSON format to show document.write (' <br><br><br><br><br> ' + json.stringify (com      ments));      }, (Error) = {alert (error); });
Second, Symbol

The object property name of ES5 is a string, which can cause conflicts of property names. For example, if you use an object provided by someone else, but want to add a new method (Mixin mode) for this object, the name of the new method may conflict with the existing method. If there is a mechanism to ensure that the name of each property is unique , then it is essential to prevent the violation of the property name fundamentally. This is why ES6 introduced the symbol.

1. The value corresponding to the symbol attribute is unique, resolving the naming conflict problem

Symbol is a new type of data that is tied to string,number,object,boolean,null,undefined.

The Symbol value is generated by a Symbol function. This means that the object's property name can now have two types, one is the original string, and the other is the new Symbol type. all attribute names are unique to the Symbol type and are guaranteed to not conflict with other property names.

let s = Symbol();typeof s; // symbol

In the above code, the variable s is a unique value. typeofoperator, which indicates that the variable s is a Symbol data type, not another type such as a string.

Note that the Symbol command cannot be used before the function new , otherwise it will be an error. This is because the generated Symbol is a value of the original type, not an object. That is, you cannot add a property because the Symbol value is not an object. Basically, it is a type of data similar to a string.

SymbolA function can accept a string as a parameter, representing a description of the Symbol instance, primarily for display in the console, or for a string, to be easily distinguishable.

let s1 = Symbol('foo');let s2 = Symbol('bar');s1 // Symbol(foo)s2 // Symbol(bar)s1.toString() // "Symbol(foo)"s2.toString() // "Symbol(bar)"

In the above code, s1 and s2 is two Symbol values. If no parameters are added, their output in the console is Symbol() not conducive to differentiation. With the parameters, they are added to the description, the output of the time can be distinguished, exactly which value.

2. Symbol value cannot be computed with other data, including string strings

let sym = Symbol('My symbol');"your symbol is " + sym// TypeError: can't convert symbol to string`your symbol is ${sym}`// TypeError: can't convert symbol to string

3. Symbol as the attribute name

Since each symbol value is unequal, this means that the symbol value can be used as an identifier for the object's property name, guaranteeing that no property of the same name will appear. This is useful for situations where an object is composed of multiple modules, which prevents a key from being accidentally overwritten or overwritten.

let mySymbol = Symbol();// 第一种写法let a = {};a[mySymbol] = 'Hello!';// 第二种写法let a = {  [mySymbol]: 'Hello!'};// 第三种写法let a = {};Object.defineProperty(a, mySymbol, { value: 'Hello!' });// 以上写法都得到同样结果a[mySymbol] // "Hello!"

Note that you cannot use the dot operator when the Symbol value is used as the object property name.a.mySymbol = 'Hello!';

4, for in, the for of traversal does not traverse the symbol property

let obj = {  username: 'Daotin',  age: 18};obj[symbol] = 'hello';obj[symbol] = 'symbol';console.log(obj);for (let i in obj) {  console.log(i);}

5. Built-in Symbol value

In addition to defining the symbol values that you use, ES6 provides 11 built-in symbol values that point to methods used internally by the language.

6, Symbol.hasinstance

Object Symbol.hasInstance , pointing to an internal method. This method is called when other objects use an instanceof operator to determine whether an instance of the object is a. For example, foo instanceof Foo inside the language, the actual invocation is Foo[Symbol.hasInstance](foo) .

7, Symbol.iterator

Object that Symbol.iterator points to the default Walker method for the object.

Third, Iterator

The following is a primer from ECMAScript 6-Nanyi

The Iterator is the meaning of the iterator (the Walker).

JavaScript's original representation of the "collection" of the data structure, mainly arrays ( Array ) and Objects ( Object ), ES6 added Map and Set . There are four sets of data that users can combine to define their own data structures, such as the members of an array whose members are Map Map objects. This requires a unified interface mechanism to handle all the different data structures.

A Iterator is such a mechanism. It is an interface that provides a unified access mechanism for a variety of data structures. Any data structure can be traversed (that is, all members of the data structure are processed sequentially) as long as the Iterator interface is deployed.

The role of Iterator:

    • Provides a unified, easy-to-access interface for a variety of data structures
    • Allows members of the data structure to be arranged in some order
    • ES6 created a new traversal command for...of loop, Iterator interface is mainly for for...of consumption.

Iterator Traversal Process:

(1) Create a pointer object that points to the starting position of the current data structure. In other words, the Walker object is essentially a pointer object.

(2) The next method of invoking the pointer object for the first time, you can point the pointer to the first member of the data structure.

(3) A second call to the next method of the pointer object points to the second member of the data structure.

(4) Constantly invoke the next method of the pointer object until it points to the end of the data structure.

Each time the next method is called, information about the current member of the data structure is returned. Specifically, it returns an object that contains both the value and done two properties. Where the Value property is the current member, the Done property is a Boolean value that indicates whether the traversal ended.

The following is an next example of a simulation method return value.

var it = makeIterator(['a', 'b']);it.next() // { value: "a", done: false }it.next() // { value: "b", done: false }it.next() // { value: undefined, done: true }function makeIterator(array) {  var nextIndex = 0;  return {    next: function() {      return nextIndex < array.length ?        {value: array[nextIndex++], done: false} :        {value: undefined, done: true};    }  };}

For a Walker object, done: false and value: undefined attributes can be omitted, so the above makeIterator function can be simply written in the following form.

function makeIterator(array) {  var nextIndex = 0;  return {    next: function() {      return nextIndex < array.length ?        {value: array[nextIndex++]} :        {done: true};    }  };}
1. Default Iterator interface

ES6 specifies that the default Iterator interface is deployed in the properties of the data structure Symbol.iterator , or that a data structure Symbol.iterator can be considered "traversed" (iterable) as long as it has attributes.

Symbol.iteratorThe property itself is a function, which is the default iterator generation function for the current data structure. Executes this function, it returns a walker. As for the property name Symbol.iterator , it is an expression that returns Symbol the property of the object iterator , which is a predefined special value of type Symbol, so put in square brackets.

const obj = {  [Symbol.iterator] : function () {    return {      next: function () {        return {          value: 1,          done: true        };      }    };  }};

In the above code, the object obj is traversed (iterable) because it has Symbol.iterator properties. Executing this property returns a Walker object. The fundamental feature of this object is that it has a next method. Each time the method is called next , it returns an information object that represents the current member, with value and done two properties.

Some of the data structures of ES6 are natively equipped with Iterator interfaces (such as arrays) that can be iterated through without any processing for...of . The reason is that these data structures are natively deployed with Symbol.iterator attributes (see below), and some data structures are not (such as objects). A Symbol.iterator data structure that deploys attributes is called a traversal interface. When this interface is called, a Walker object is returned.

The data structure of the native Iterator interface is as follows.

    • Array
    • Map
    • Set
    • String
    • TypedArray
    • The arguments object of the function
    • NodeList Object

The following example is an array of Symbol.iterator properties.

let arr = ['a', 'b', 'c'];let iter = arr[Symbol.iterator]();iter.next() // { value: 'a', done: false }iter.next() // { value: 'b', done: false }iter.next() // { value: 'c', done: false }iter.next() // { value: undefined, done: true }

In the above code, the variable arr is an array, originally born with a walker interface, deployed on arr top of the Symbol.iterator property. So, calling this property, you get the Walker object.

For native deployments of the Iterator interface data structures, the for...of loops automatically traverse them without having to write their own walker-generated functions. In addition, other data structures (mainly objects) of the Iterator interface, all need to be deployed on the Symbol.iterator property itself, so that it will be iterated for...of through.

If an object is to have an for...of Iterator interface that can be called by a loop, the Symbol.iterator Walker generation method must be deployed on the property (the object on the prototype chain has that method as well).

2, call the Iterator interface of the occasion
    • Use the deconstructed assignment and ... The iterator interface is called when the three-point operator
let arr1 = [1, 2, 3, 4, 5];let [value1, ...arr2] = arr1;

For: Of.. Traverse

// 原生测试  数组let arr3 = [1, 2, 'kobe', true];for (let i of arr3) {  console.log(i);}// 字符串  stringlet str = 'abcdefg';for (let item of str) {  console.log(item);}

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.