@Lxyour
2018-09-21T13:32:54.000000Z
字数 3346
阅读 1347
JavaScript
ECMAScript6(ECMAScript 2015 ,ES5,ES2016)技术已经在前端圈子很流行了,这些新的标准给前端开发人员带来了很多惊喜,提供的语法糖使复杂的操作变得简单。这里总结了一些常用的新特性范例代码,希望初学者能快速了解这些新的JavaScript规范。
不要用var,而是用let 和 const 。const声明一个只读的常量,let用来声明变量,const 和 let 都是块级作用域。
const PLUS = 'PLUS';let availableId = 0;availableId ++;
模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。
const user = 'world';console.log(`hello ${user}`); // hello world// 多行(所有的空格和缩进都会被保留在输出之中)const content = `Hello ${firstName},Thanks for ordering ${qty} tickets to ${event}.`;
function log(user = 'World') {console.log(user);}log() // World
ES6 允许使用“箭头”(=>)定义函数。
函数的快捷写法,不需要通过 function 关键字创建函数,并且还可以省略 return 关键字。
同时,箭头函数还会继承当前上下文的 this 关键字,即:函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
// ES6function Timer() {this.s1 = 0;setInterval(() => this.s1++, 1000);}// 等同于ES5function Timer() {this.s1 = 0;setInterval((function () {this.s1++;}).bind(this), 1000);}const timer = new Timer();setTimeout(() => console.log('s1: ', timer.s1), 3100);// s1:3
var object = {name: "Name",arrowGetName: () => this.name,regularGetName: function() { return this.name },arrowGetThis: () => this,regularGetThis: function() { return this }}console.log(this.name)console.log(object.arrowGetName());console.log(object.arrowGetThis());console.log(this)console.log(object.regularGetName());console.log(object.regularGetThis());
结果:
this.name ->object.arrowGetName() ->object.arrowGetThis() -> [object Window]this -> [object Window]object.regularGetName() -> Nameobject.regularGetThis() -> {"name":"Name"}
import 用于引入模块,export 用于导出模块。
//导出默认, counter.jsexport default function counter() {// ...}import counter from 'counter';// 普通导出和导入,reducer.jsexport const injectReducer = ( ) => {//...}import { injectReducer } from 'reducers'// 引入全部并作为 reducers 对象import * as reducers from './reducers';// 别名导出 as.jsvar a ='乐潇游';var b ='es6';var c = 'web';export {a as x,b as y,c as z}// 导入import { x } from 'as';
// 数组let [a, b, c] = [1, 2, 3];a // 1//对象let { foo, bar } = { foo: "aaa", bar: "bbb" };foo // "aaa"
函数的参数也可以使用解构赋值。
function add ([x, y]) {return x + y;}add([1, 2]); // 3
从作为函数实参的对象中提取数据
function userId({id}) {return id;}function whois({displayName: displayName, fullName: {firstName: name}}){console.log(displayName + " is " + name);}var user = {id: 42,displayName: "jdoe",fullName: {firstName: "John",lastName: "Doe"}};console.log("userId: " + userId(user)); // "userId: 42"whois(user); // "jdoe is John"
const foo = 'bar';const baz = {foo};baz // {foo: "bar"}// 等同于const baz = {foo: foo};
除了属性简写,方法也可以简写。
const o = {method() {return "Hello!";}};// 等同于const o = {method: function() {return "Hello!";}};
扩展运算符(spread)是三个点(...)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
组装数组
const a = [1, 2];const b = [...a, 3];b // [1,2,3]
获取数组部分
const arr = ['a', 'b', 'c'];const [first, ...rest] = arr;rest; // ['b', 'c']// With ignoreconst [first, , ...rest] = arr;rest; // ['c']
还可收集函数参数为数组。
function directions(first, ...rest) {console.log(rest);}directions('a', 'b', 'c'); // ['b', 'c'];
代替 apply。
function foo(x, y, z) {}const args = [1,2,3];// 下面两句效果相同foo.apply(null, args);foo(...args);
组装对象
const a = { x : 1, y : 2 }const b = { ...a, z : 3 }b // {x:1, y: 2, z: 3}
Promise 用于更优雅地处理异步请求。比如发起异步请求:
fetch('/api/todos').then(res => res.json()).then(data => ({ data })).catch(err => ({ err }));
定义 Promise 。
const delay = (timeout) => {return new Promise(resolve => {setTimeout(resolve, timeout);});};delay(1000).then(() => {console.log('executed');});
这里只是简洁地总结了常用的ES6特性,更全、更详尽的知识可以学习阮一峰老师出的《ECMAScript 6 入门》