[关闭]
@Lxyour 2018-09-21T13:32:54.000000Z 字数 3346 阅读 1136

ES6常用新特性总结

JavaScript


ECMAScript6(ECMAScript 2015 ,ES5,ES2016)技术已经在前端圈子很流行了,这些新的标准给前端开发人员带来了很多惊喜,提供的语法糖使复杂的操作变得简单。这里总结了一些常用的新特性范例代码,希望初学者能快速了解这些新的JavaScript规范。

变量声明

let 和 const

不要用var,而是用letconstconst声明一个只读的常量,let用来声明变量,constlet 都是块级作用域。

  1. const PLUS = 'PLUS';
  2. let availableId = 0;
  3. availableId ++;

模板字符串

模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。

  1. const user = 'world';
  2. console.log(`hello ${user}`); // hello world
  3. // 多行(所有的空格和缩进都会被保留在输出之中)
  4. const content = `
  5. Hello ${firstName},
  6. Thanks for ordering ${qty} tickets to ${event}.
  7. `;

默认参数

  1. function log(user = 'World') {
  2. console.log(user);
  3. }
  4. log() // World

箭头函数

ES6 允许使用“箭头”(=>)定义函数。
函数的快捷写法,不需要通过 function 关键字创建函数,并且还可以省略 return 关键字。
同时,箭头函数还会继承当前上下文的 this 关键字,即:函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。

  1. // ES6
  2. function Timer() {
  3. this.s1 = 0;
  4. setInterval(() => this.s1++, 1000);
  5. }
  6. // 等同于ES5
  7. function Timer() {
  8. this.s1 = 0;
  9. setInterval((function () {
  10. this.s1++;
  11. }).bind(this), 1000);
  12. }
  13. const timer = new Timer();
  14. setTimeout(() => console.log('s1: ', timer.s1), 3100);
  15. // s1:3

this 是如何工作的?

  1. var object = {
  2. name: "Name",
  3. arrowGetName: () => this.name,
  4. regularGetName: function() { return this.name },
  5. arrowGetThis: () => this,
  6. regularGetThis: function() { return this }
  7. }
  8. console.log(this.name)
  9. console.log(object.arrowGetName());
  10. console.log(object.arrowGetThis());
  11. console.log(this)
  12. console.log(object.regularGetName());
  13. console.log(object.regularGetThis());

结果:

  1. this.name ->
  2. object.arrowGetName() ->
  3. object.arrowGetThis() -> [object Window]
  4. this -> [object Window]
  5. object.regularGetName() -> Name
  6. object.regularGetThis() -> {"name":"Name"}

模块的 Import 和 Export

import 用于引入模块,export 用于导出模块。

  1. //导出默认, counter.js
  2. export default function counter() {
  3. // ...
  4. }
  5. import counter from 'counter';
  6. // 普通导出和导入,reducer.js
  7. export const injectReducer = ( ) => {
  8. //...
  9. }
  10. import { injectReducer } from 'reducers'
  11. // 引入全部并作为 reducers 对象
  12. import * as reducers from './reducers';
  13. // 别名导出 as.js
  14. var a ='乐潇游';
  15. var b ='es6';
  16. var c = 'web';
  17. export {
  18. a as x,
  19. b as y,
  20. c as z
  21. }
  22. // 导入
  23. import { x } from 'as';

更多参考:es6环境中,export与import使用方法

ES6 对象和数组

解构赋值

  1. // 数组
  2. let [a, b, c] = [1, 2, 3];
  3. a // 1
  4. //对象
  5. let { foo, bar } = { foo: "aaa", bar: "bbb" };
  6. foo // "aaa"

函数的参数也可以使用解构赋值。

  1. function add ([x, y]) {
  2. return x + y;
  3. }
  4. add([1, 2]); // 3

从作为函数实参的对象中提取数据

  1. function userId({id}) {
  2. return id;
  3. }
  4. function whois({displayName: displayName, fullName: {firstName: name}}){
  5. console.log(displayName + " is " + name);
  6. }
  7. var user = {
  8. id: 42,
  9. displayName: "jdoe",
  10. fullName: {
  11. firstName: "John",
  12. lastName: "Doe"
  13. }
  14. };
  15. console.log("userId: " + userId(user)); // "userId: 42"
  16. whois(user); // "jdoe is John"

属性的简洁表示法

  1. const foo = 'bar';
  2. const baz = {foo};
  3. baz // {foo: "bar"}
  4. // 等同于
  5. const baz = {foo: foo};

除了属性简写,方法也可以简写。

  1. const o = {
  2. method() {
  3. return "Hello!";
  4. }
  5. };
  6. // 等同于
  7. const o = {
  8. method: function() {
  9. return "Hello!";
  10. }
  11. };

扩展运算符

扩展运算符(spread)是三个点(...)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
组装数组

  1. const a = [1, 2];
  2. const b = [...a, 3];
  3. b // [1,2,3]

获取数组部分

  1. const arr = ['a', 'b', 'c'];
  2. const [first, ...rest] = arr;
  3. rest; // ['b', 'c']
  4. // With ignore
  5. const [first, , ...rest] = arr;
  6. rest; // ['c']

还可收集函数参数为数组。

  1. function directions(first, ...rest) {
  2. console.log(rest);
  3. }
  4. directions('a', 'b', 'c'); // ['b', 'c'];

代替 apply。

  1. function foo(x, y, z) {}
  2. const args = [1,2,3];
  3. // 下面两句效果相同
  4. foo.apply(null, args);
  5. foo(...args);

组装对象

  1. const a = { x : 1, y : 2 }
  2. const b = { ...a, z : 3 }
  3. b // {x:1, y: 2, z: 3}

Promise

Promise 用于更优雅地处理异步请求。比如发起异步请求:

  1. fetch('/api/todos')
  2. .then(res => res.json())
  3. .then(data => ({ data }))
  4. .catch(err => ({ err }));

定义 Promise 。

  1. const delay = (timeout) => {
  2. return new Promise(resolve => {
  3. setTimeout(resolve, timeout);
  4. });
  5. };
  6. delay(1000).then(() => {
  7. console.log('executed');
  8. });

写在最后

这里只是简洁地总结了常用的ES6特性,更全、更详尽的知识可以学习阮一峰老师出的《ECMAScript 6 入门》

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注