Home  >  Article  >  Web Front-end  >  What's new in es6

What's new in es6

青灯夜游
青灯夜游Original
2022-04-13 14:27:433194browse

ES6 new features: 1. Use const and let to declare variables, both variables are block-level scope; 2. Template string, the syntax "`string`" allows string concatenation More concise; 3. Arrow function, which can solve the problem of this pointing; 4. Extension operator, expand the iterable object into its separate elements; 5. Modularization, etc.

What's new in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

ECMAScript 6 (ES6) has basically become the industry standard. Its popularity is much faster than ES5. The main reason is that modern browsers support ES6 very quickly, especially Chrome and Firefox browsers, which already support it. Most features in ES6.

The following is a detailed explanation of the commonly used new ES6 features:

1. Different variable declarations: const and let

Before, JS did not have block-level scope. Const and let filled this convenient gap. Both const and let were block-level scope.

ES6 recommends using let to declare local variables, compared to the previous var (no matter where it is declared, it will be regarded as declared at the top of the function) The difference between let and var declarations:

var x = '全局变量';
{
  let x = '局部变量';
  console.log(x); // 局部变量
}
console.log(x); // 全局变量

let means declaring variables, while const means declaring constants. Both are block-level scopes; variables declared with const will be considered constants, which means that their values ​​are After the setting is completed, it cannot be modified:

const a = 1
a = 0 //报错

If const is an object, the value contained in the object can be modified. To put it more abstractly, it just means that the address pointed to by the object has not changed:

const student = { name: 'cc' }

student.name = 'yy';// 不报错
student  = { name: 'yy' };// 报错

There are a few points to note:

  • The variable declared by the let keyword does not have a variable Hoisting feature
  • let and const declarations are only valid in the closest block (within curly braces)
  • When using constant const declarations, please use uppercase variables, such as: CAPITAL_CASING
  • const must be assigned when declared

2. Template string

in ES6 Previously, we often handled template strings like this: Build templates through "\" and " "

$("body").html("This demonstrates the output of HTML \
content to the page, including student's\
" + name + ", " + seatNumber + ", " + sex + " and so on.");

And for ES6

  • Basic string formatting. Embed expressions in strings for concatenation. Use ${} to define it;

  • ES6 backtick (``) can be done directly;

ES6 supports template strings, making the string The splicing is more concise and intuitive.

$("body").html(`This demonstrates the output of HTML content to the page, 
including student's ${name}, ${seatNumber}, ${sex} and so on.`);

3. Arrow Functions

This is one of the most exciting features in ES6. => is not just an abbreviation for the keyword function, it also brings other benefits. The arrow function shares the same this with the code surrounding it, which can help you solve the pointing problem of this. Experienced JavaScript developers are familiar with patterns such as var self = this; or var that = this. But with =>, this pattern is no longer needed.

The three most intuitive characteristics of arrow functions.

  • The function keyword is not required to create a function
  • Omit the return keyword
  • Inherit the this keyword of the current context
// ES5
var add = function (a, b) {
    return a + b;
};
// 使用箭头函数
var add = (a, b) => a + b;

// ES5
[1,2,3].map((function(x){
    return x + 1;
}).bind(this));
    
// 使用箭头函数
[1,2,3].map(x => x + 1);

Details: When your function has one and only one parameter, you can omit the parentheses. When your function returns one and only one expression, you can omit {} and return;

4. Function parameter default values

Before ES6, we often defined the default values ​​of parameters like this:

// ES6之前,当未传入参数时,text = 'default';
function printText(text) {
    text = text || 'default';
    console.log(text);
}

// ES6;
function printText(text = 'default') {
    console.log(text);
}

printText('hello'); // hello
printText();// default

5. Spread operator

The spread operator … was introduced in ES6, which expands an iterable object into its separate elements. The so-called iterable object is any object that can be traversed using a for of loop, such as : Array, string, Map, Set, DOM node, etc.

Extension operator...You can expand the array expression or string at the syntactic level during function call/array construction; you can also expand the object expression by Expand in key-value manner.

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 in function parameters, it is a Rest operator: When used When passing parameters to a function, it is a Rest operator:

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

6. Binary and octal literals

ES6 supports binary And octal literals can be converted to octal values ​​by adding 0o or 0O in front of the number:

let oValue = 0o10;
console.log(oValue); // 8
 
let bValue = 0b10; // 二进制使用 `0b` 或者 `0B`
console.log(bValue); // 2

7. Object and array destructuring

// 对象
const student = {
    name: 'Sam',
    age: 22,
    sex: '男'
}
// 数组
// const student = ['Sam', 22, '男'];

// ES5;
const name = student.name;
const age = student.age;
const sex = student.sex;
console.log(name + ' --- ' + age + ' --- ' + sex);

// ES6
const { name, age, sex } = student;
console.log(name + ' --- ' + age + ' --- ' + sex);

8. Object super class

ES6 allows the use of the super method 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 from the Child

9.for...of and for...in

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

let letter = ['a', 'b', 'c'];
letter.size = 3;
for (let letter of letters) {
  console.log(letter);
}
// 结果: a, b, c

for...in 用来遍历对象中的属性:

let stu = ['Sam', '22', '男'];
stu.size = 3;
for (let stu in stus) {
  console.log(stu);
}
// 结果: Sam, 22, 男

10.ES6中的类

ES6 中支持 class 语法,不过,ES6的class不是新的对象继承模型,它只是原型链的语法糖表现形式。

函数中使用 static 关键词定义构造函数的的方法和属性:

class Student {
  constructor() {
    console.log("I'm a student.");
  }
 
  study() {
    console.log('study!');
  }
 
  static read() {
    console.log("Reading Now.");
  }
}
 
console.log(typeof Student); // function
let stu = new Student(); // "I'm a student."
stu.study(); // "study!"
stu.read(); // "Reading Now."

类中的继承和超集:

class Phone {
  constructor() {
    console.log("I'm a phone.");
  }
}
 
class MI extends Phone {
  constructor() {
    super();
    console.log("I'm a phone designed by xiaomi");
  }
}
 
let mi8 = new MI();

extends 允许一个子类继承父类,需要注意的是,子类的constructor 函数中需要执行 super() 函数。 当然,你也可以在子类方法中调用父类的方法,如super.parentMethodName()。 在 这里 阅读更多关于类的介绍。

有几点值得注意的是:

  • 类的声明不会提升(hoisting),如果你要使用某个 Class,那你必须在使用之前定义它,否则会抛出一个 ReferenceError 的错误
  • 在类中定义函数不需要使用 function 关键词

11、模块化(Module)

ES5不支持原生的模块化,在ES6中模块作为重要的组成部分被添加进来。模块的功能主要由 export 和 import 组成。每一个模块都有自己单独的作用域,模块之间的相互调用关系是通过 export 来规定模块对外暴露的接口,通过import来引用其它模块提供的接口。同时还为模块创造了命名空间,防止函数的命名冲突。

导出(export)

ES6允许在一个模块中使用export来导出多个变量或函数。

导出变量

//test.js
export var name = 'Rainbow'

心得:ES6不仅支持变量的导出,也支持常量的导出。 export const sqrt = Math.sqrt;//导出常量

ES6将一个文件视为一个模块,上面的模块通过 export 向外输出了一个变量。一个模块也可以同时往外面输出多个变量。

 //test.js
 var name = 'Rainbow';
 var age = '24';
 export {name, age};

导出函数

// myModule.js
export function myModule(someArg) {
  return someArg;
}

导入(import)

定义好模块的输出以后就可以在另外一个模块通过import引用。

import {myModule} from 'myModule';// main.js
import {name,age} from 'test';// test.js

心得:一条import 语句可以同时导入默认函数和其它变量。import defaultMethod, { otherMethod } from 'xxx.js';

【相关推荐:javascript视频教程web前端

The above is the detailed content of What's new in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn