ES6 给 JavaScript 带来了很深刻的变化。 它完全改变了我们使用 JavaScript 的方式。 ES7是在ES6之上的一个微小更新。 让我们看看 ES6 更新中带来的变化。本文起初是我的学习笔记,现在我和大家分享一下。
支持UNICODE标准版本8
它将允许使用笑脸,一个可以使用 unicode 声明为转义字符的变量。
示例:
- var \u{102C0} = { \u{102C0} : 2 };
- return \u{102C0};
二进制,十六进制和十进制数
- hex – 16进制 – 以
0x
开头 - Oct — 8进制 — 以
0o
开头 - Binary — 2进制 — 以
0b
开头
- var decimalLit = 15;
- var hexadecimalLit = 0xF;
- var octalLit = 0o17;
- var binaryLit = 0b1111;
- console.log(decimalLit == hexadecimalLit);
- console.log(decimalLit == octalLit);
- console.log(decimalLit == binaryLit);
字符串模板
以前使用+
连接字符串,现在可以使用 ` 。
以前版本:
- var message = "The user "+ user.firstName + "" + user.lastName +
- " cannot be "+ action + "because "+ validationError;
新版本:
- var message = `The user ${user.firstName} ${user.lastName} cannot be
- ${action} because ${validationError}`;
注意:
be
和 ${action}
之间的换行是因为反引号字符串也称为“多行文字”。这意味着空格保留在字符串中,因此上面的消息将显示成两行上。 它会在“be”之后换行,然后在继续之前显示两个空格(因为代码缩进两个空格)。
变量声明
var
声明的变量可以被重新分配,所以我们现在用 let
关键字不允许这样做。其他都是相同的。
- var msg = "Howdy";
- var msg = "Hello there"; // 合理的,只是重新分配
另一方面:
- let message = `This is your message.`;
- let message = `This is another message.`; // 错误! 不能重新声明早期声明的变量 `message`
CONST 关键字
等同于java中的 final
和 C/C++中的 const
。
- const message = `This is your message.`;
- message = `This is your second message.`; // 错误!不能重新分配一个 `const` 变量
块级作用域
var
声明的变量没有块级作用域,只有函数作用域。
let
和 const
声明的变量的作用域在声明它们的语句块中。
解构赋值
它将数组分解成一个个的元素,保持原始数组不变。 这个过程将值映射到相同的变量名中。
示例:
- let names = ["Ted", "Jenni", "Athen"];
- let [ted, jenni, athen] = names;
- console.log(ted, jenni, athen); // 打印 "Ted", "Jenni", "Athen"
- // 类似于下面的赋值语句
- var ted = names[0];
- var jenni = names[1];
- var athen = names[2];
对象解构
示例:
- var url = "http://www.newardassociates.com/#/speaking";
- var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
- var [protocol, fullhost, fullpath] = parsedURL;
- console.log(protocol); // “http”
- let point = { x:2, y: 5 };
- let {x, y} = point;
- console.log(x, y); // prints 2, 5
- let point = { x:2, y: 5 };
- let {y, x} = point;
- console.log(x, y); // prints 2, 5
- let {y: pty, x: ptx} = point;
- console.log(ptx, pty); // prints 2, 5
左侧表示匹配的名称,右侧表示实际声明的变量名称:
- let rect = { lowerLeft: { x:0, y:0 }, upperRight: { x:3, y:4} };
- let { lowerLeft: { x:llx, y: lly }, upperRight: { x:urx, y:ury } }
- = rect;
- console.log(llx, lly, urx, ury); // prints “0 0 3 4
在方法调用是解构对象参数
- let person = {
- firstName: "Ted",
- lastName: "Neward",
- age: 45,
- favoriteLanguages: ["ECMAScript", "Java", "C#", "Scala", "F#"]
- }
- function displayDetails({firstName, age}) {
- console.log(`${firstName} is ${age} years old`);
- }
- displayDetails(person);
默认参数
现在我们可以像 C/C++ 那样为函数参数提供默认值。
- let sayHello = function(message = "Hello world!") {
- console.log(message);
- }
- sayHello(); // prints "Hello world!"
- sayHello("Howdy!"); // prints "Howdy!"
函数的剩余参数:传递一个参数列表
在过去,您可能已经通过访问内置的 arguments
参数来完成此操作,该参数被静默构造并传递给每个函数调用:
如果传递给该函数的参数超过了定义的参数数目,那么它们会被添加到 arguments
中。
通过以下方式访问:
- var args = Array.prototype.slice.call(arguments, .length);
在ES6中,我们现在可以实用 JAVA 风格的语法来捕获一个值的列表。
示例:
- function greet(firstName, …args) {
- console.log("Hello",firstName);
- args.forEach(function(arg) { console.log(arg); });
- }
- greet("Ted");
- greet("Ted", "Hope", "you", "like", "this!");
扩展操作符:同剩余参数相反
该操作符把数组分成单个变量,最简单的用例是串联数组。
- let arr1 = [0, 1, 2];
- let arr2 = [...arr1, 3, 4, 5];
- console.log(arr2); // prints 0,1,2,3,4,5
- // 重要的用例:
- function printPerson(first, last, age) {
- console.log(first, last age);
- }
- let args = ["Ted", "Neward", 45];
- printPerson(...args);
箭头函数
关键字 function
可以实用箭头操作符 =>
替代。
示例:
- function(arg1, arg2){//something here}
- // 上面的函数可以写成:
- (arg1, arg2) => {//something here}
注意:
另请注意,如果箭头函数的主体是单个表达式产生一个值,则不需要显式返回(不需要实用 return
)。相反,该单个表达式隐式地返回给箭头函数的调用者。然而,如果主体不止一个语句或表达式,那么大括号是必需的,并且任何返回的值都必须通过 return
语句返回给调用者。
愚人码头注:实用剪头函数的时候还应该特别注意箭头函数体内的 this
,请查看:ES2015 中的箭头函数和词法 this
迭代数组
in
操作符。
- let arr = ["janishar", "ali", "anwar"]
- let displayArr = function(arr) {
- for (let x in arr) {
- console.log(x);
- }
- };
如果 this 是在全局作用域下引用,那么他就指向全局的变量,函数或对象
this
指向调用函数的对象。
示例:
- let displayThis = function() {
- for (let m in this) {
- console.log(m);
- }
- };
- displayThis(); // this == global object
- let bob = {
- firstName: "Bob",
- lastName: "Robertson",
- displayMe: displayThis
- };
- bob.displayMe(); // this == bob
在 NODE JS require(‘events’) 用来订阅-发布模块
- let EventEmitter = require('events');
- let ee = new EventEmitter();
- ee.on('event', function() {
- console.log("function event fired", this);
- });
- ee.emit('event');
注意:
如果你使用 EventEmitter
注册一个遗留函数,this
将是在运行时确定。但是如果你使用 EventEmitter 注册了一个箭头函数,那么 this
将在定义箭头函数时被绑定。
生成器函数: 类似于反应式编程中的流
ES6中使用生成器函数实现无限流。
示例:
- function* getName() {
- yield "Ted";
- yield "Charlotte";
- yield "Michael";
- yield "Matthew";
- }
- let names = getName();
- console.log(names.next().value);
- console.log(names.next().value);
- console.log(names.next().value);
- console.log(names.next().value);
- console.log(names.next().value);
该函数将按顺序打印每个名称。当names
用完时,它将打印 undefined
。
for-of 语句
for-of
语句与 for-in
相似。
for-of
和 for-in
之间存在细微的差别,但在在大多数情况下,您可以使用 for-of
替换旧的语法。它只是增加了使用 generators(生成器) 的能力。
JavaScript 基于对象的环境
JavaScript 不是基于类的,而是基于对象的环境。在基于对象的环境中,没有类,每个对象都是从其他现有对象中克隆出来的。 当一个对象被克隆时,它保留了对原型的隐式引用。
定义一个类
- class Person{}
- let p = new Person();
类的构造器
- class Person{
- constructor(firstName, lastName, age){
- this.firstName = firstName;
- this.lastName = lastName;
- this.age = age;
- }
- }
- let ted = new Person("Ted", "Neward", 45);
- console.log(ted);
Getter 和 Setter
- class Person {
- constructor(firstName, lastName, age) {
- console.log(arguments);
- this.firstName = firstName;
- this.lastName = lastName;
- this.age = age;
- }
- get firstName() { return this._firstName; }
- set firstName(value) { this._firstName = value; }
- get lastName() { return this._lastName; }
- set lastName(value) { this._lastName = value; }
- get age() { return this._age; }
- set age(value) { this._age = value; }
- }
注意:
this._<field_name>
指向通过构造器添加的变量 </field_name><field_name>
。
原型链
很早以前,JavaScript 就已经将原型链从一个对象维护到另一个对象上。您可能会假设原型链接类似于 Java 或 C++ / C# 中的继承,但这两种技术之间只有一个真正的相似之处:当 JavaScript 需要解析对象上的标识符时,如果该标识符不(直接)对象上,那么它会沿着原型链向上匹配。
继承
- class Author extends Person{
- constructor(firstName, lastName, age, subject){
- super(firstName, lastName, age);
- this.subject = subject;
- }
- get subject() { return this._subject; }
- set subject(value) { this._subject = value; }
- writeArticle() {
- console.log(
- this.firstName,
- "just wrote an article on",
- this.subject
- );
- }
- }
- let mark = new Author("Mark", "Richards", 55, "Architecture");
- mark.writeArticle();
静态或单例
静态字段:
ECMAScript 6 没有明确规定静态属性或字段,但我们可以间接创建。
- class Person{
- constructor(firstName, lastName, age){
- console.log(arguments);
- // 如果Person不存在该变量,
- // 就要引入一个新的字段;
- // 否则,只是引用该变量
- if (typeof(Person.population === 'undefined'))
- Person.population = 0;
- Person.population++;
- this.firstName = firstName;
- this.lastName = lastName;
- this.age = age;
- }
- //...as before
- }
静态方法:
要定义静态方法,您可以在类声明中使用 static
关键字来定义函数:
- class Person{
- //...as before
- static haveBaby() {
- return Person.population++;
- }
- }
模块: import(导入) 和 export(导出):
截至2017年5月19日,nodejs不支持此功能
export(导出):
如果您有一个文件要作为模块使用 – 我们称之为输出 – 您只需 export(导出) 想要在其他地方使用的标识符,如下所示:
- 导出一个函数
- output.js
- export function output() {
- console.log("OUT: ", arguments);
- }
import(导入):
在其他地方导入上面导出的函数
- import { out } from 'output.js';
- out("I'm using output!");
为了使用这个模块,您必须知道您想要导入的所有名称。(尽管有些人可能会认为这有一种好处,因为它可以确保不会导入不知道的任何标识符。)如果想要从模块中获取所有导出的名称,可以使用通配符( *
)导入语法,但是需要定义一个模块名称,以便你在其范围内操作:
导入全部:
- import * as Output from 'output'; // 你也可以忽略 `.js` 后缀
- Output.out("I'm using output!");
Symbol
Symbol 是一种类型。 Symbol 的一个实例是唯一的名称,不能在其他地方重复。 它用于以安全的方式保持一个变量。Symbol 的主要功能是帮助程序员避免跨库的名称冲突。一开始有点难理解,试着将 Symbol 作为基于字符串的唯一哈希值来考虑即可。
集合:
Array,Map 和 Set
Map:
Map 是一个组键/值对。
- 它包含方法
get()
和set()
,分别用来查找和设置 键/值 对。 clear()
将完全清空该集合。keys()
返回 Map 中键的可迭代集合。values()
也是一样的道理。
另外,类似于 Array ,Map 包含函数式语言的方法,如 forEach()
,它们可以在 Map 上运行。
示例:
- let m = new Map();
- m.set('key1', 'value1');
- m.set('key2', 'value2');
- m.forEach((key, value, map) => {
- console.log(key,'=',value,' from ', map);
- })
- console.log(m.keys());
- console.log(m.values());
Set:
Set,更像是传统的对象集合,可以将对象简单地添加到集合中。但是 Set 会依次检查每个对象,以确保它不是集合中已经存在的值。
示例:
- let s = new Set();
- s.add("Ted");
- s.add("Jenni");
- s.add("Athen");
- s.add("Ted"); // 重复的!
- console.log(s.size); // 3
弱引用
WeakMaps 和 WeakSets ,它们通过弱引用来保持 map 和 set 的值,而不是传统的强引用。
Promise
ES6 内置了 Promise。 (我们将单独用一篇文章介绍 promise 。)
Proxy 代理
Proxy允许对象在被可访问之前修改它的行为。
推荐 Ted Neward 的优秀的文章 (如果你想读这篇文章, 请点击 这里。)
原文: http://www.css88.com/archives/8189