Learn the ES6 of the Web from scratch (iii) ES6 Basic grammar One

Source: Internet
Author: User

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

  • Github:https://github.com/daotin/web
  • Public number: The top of the Web front
  • Blog Park: http://www.cnblogs.com/lvonve/
  • csdn:https://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, let

Function: Similar to VAR, used to declare a variable.

The difference between let and Var:

    • Valid within a block scope
    • Cannot repeat declaration
    • No preprocessing, no elevation
  <script type="text/javascript">    console.log(res); //不会预处理, 不存在提升,报错    // 不能重复声明    let res = 10;    let res = 10; // 报错  </script>

Application: Loop traversal plus monitoring

Let's start with an example:

<body>  <button>测试1</button>  <button>测试2</button>  <button>测试3</button>  <script type="text/javascript">    let btns = document.getElementsByTagName('button');    for (var i = 0; i < btns.length; i++) {      btns[i].onclick = function () {        alert(i);      }    }  </script></body>

How much do we print each time we click the button?

Result: The print is all 2. because the callback function is written in a overwrite operation . How to solve?

Method one: Use closures.

for (var i = 0; i < btns.length; i++) {   (function(){      btns[i].onclick = function () {        alert(i);      }   })(i);  }

In this way, each callback function has its own interval, and each interval does not interfere with each other. Let's just have this feature.

Method Two: Change the Var for the for loop to let.

Second, the const

Function: Defines a constant.

Features: Can not be modified, other features with Let.

const uName = 'Daotin';
Third, the solution assignment of the variable

Understanding: Extracts data from an object or array and assigns a value to a variable (multiple).

1, the object's deconstruction assigns the value

Before we get the properties of an object, we define the variable and then receive the object's property value.

let obj = {name : 'kobe', age : 39};let name = obj.name;let age = obj.age;console.log(name, age);

The object's deconstruction assignment can do this:

let {name, age} = obj;console.log(name, age);

Attention:
1, the object's deconstruction assignment must use curly braces {}

2. The variable name inside the curly braces must be the same as the property name inside obj

3, you can define only a subset of the variables to receive a portion of the Obj property, do not need to receive all.

2. The deconstruction assignment of the array

The array has no array name for the object, but it can be used with subscript. So the variable name here can be random.

let arr = ['abc', 23, true];let [a, b, c] = arr;console.log(a, b, c);

Attention:

1, the solution assignment of the array must use the brackets []

If you want to take only a few of these values, the variables can be separated by commas.

let [,,a,,] = arr;

if the number of variables defined is more than the number of arrays, the value of the extra variable is undefined .

Four, template string

Function: simplifies concatenation of strings.

Attention:

1. The template string must contain "'";

2, the change of part of the use of the ${xxx} definition

let obj = {  name: 'anverson',  age: 41};// 我们之前拼接字符串用的是+console.log('我叫:' + obj.name + ', 我的年龄是:' + obj.age);// 使用模板字符串的方式console.log(`我叫:${obj.name}, 我的年龄是:${obj.age}`);
V. Simplified wording of objects

If there are variables and objects with the same property name, the previous notation is an assignment operation:

let a = 1;let b = 2;let Obj = {  a: a,  b: b,};

Now, if the variables and objects have the same property names, you can do the following:

let a = 1;let b = 2;let Obj = {  a,  b,};

For an object's properties, if it is a function, it can also be abbreviated:

The previous wording was:

let Obj = {  foo: function(){    //...  }};

Now the notation is: (remove colon and function)

let Obj = {  foo(){    //...  }};
Six, arrow function

Function: The function of the arrow is to define the anonymous function.

An anonymous function with the following conditions can use the arrow function:

let foo = function () {};// 转换成箭头函数let foo = () => {};//------------------------------let Obj = {  foo: function () {  }}// 转换成箭头函数let Obj = {  foo: () => {  }}

Basic syntax (parameters):

1, anonymous function no parameters: () can not be omitted, the role of the placeholder.let foo = () => {};

2, only one parameter: () can be omitted, or can not be omitted.let foo = a => {};

3, multiple parameters, () can not be omitted.let foo = (a,b) => {};

Basic syntax (function body):

1, the function body has only one statement: you can omit {}, and return the result by default (no need to return).

let foo = (x, y) => x + y;console.log(foo(1, 2));

2, the function body if there are multiple statements, you need to enclose {}, if you need to return the content, you need to add a return.

    let foo = (x, y) => {      console.log(x, y);      return x + y;    };    console.log(foo(1, 2));

Features of the arrow function:

1. Introduction

2, the arrow function does not have its own this, the arrow function of this is not called when the decision, but at the time of the definition of the object is its this. (meaning: If there is a function in the outer layer of the arrow function, if so, the this of the arrow function is this of the outer function, and if not, the window)

  <script type="text/javascript">    let foo = () => {      console.log(this);    };    foo(); // window 对象    let Obj1 = {      bar() {        let foo = () => {          console.log(this);        };        foo();      }    };    Obj1.bar();  // Obj1 对象,箭头函数外层有函数bar,bar里面的this是Obj1.    let Obj2 = {      bar: () => {        let foo = () => {          console.log(this);        };        foo();      }    };    Obj2.bar(); // window 对象,箭头函数外层有函数bar,bar函数也是箭头函数,bar的外层没有函数,所以bar里面的this是window,所以foo里面的this也是window。  </script>
73-point (variable-parameter) operator

Role:

1, used to replace arguments but more flexible than arguments,

Arguments is a pseudo-array, but the three-point operator is a true array , and you can use methods such as ForEach.

The 2, three-point (variadic) operator can only be the last-part parameter. But there are parameters that can be used in front of the placeholder.

3. Extension operators

    let arr = [1, 6];    let arr1 = [2, 3, 4, 5];    arr = [1, ...arr1, 6];    console.log(arr); // [1,2,3,4,5,6]    console.log(...arr); // 1 2 3 4 5 6

Syntax: ...数组名 : Represents the traversal of all elements of an array.

Viii. parameter Default value

Function: Default values in Parameters are used when the parameter is not passed in.

    <script type="text/javascript">        //定义一个点的坐标        function Point(x = 12, y = 12) { // 形参的默认值            this.x = x;            this.y = y;        }        let p = new Point();        console.log(p);        let point = new Point(25, 36);        console.log(point);    </script>

Learn the ES6 of the Web from scratch (iii) ES6 Basic grammar One

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.