ES6是 ECMAScript 6 的简称,它是JavaScript语言的下一代标准,已经在2015年6月正式发布了。今天介绍下ES6中有哪些新语法。
开发环境搭建 1 2 3 4 5 6 新建如下目录结构: ES6test dist src index.js index.html
index.js中的内容如下:
1 2 let a = 1; console.log(a);
在终端执行 npm init -y 后,会生成 package.json 文件,文件内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 { "name" : "ES6test" , "version" : "1.0.0" , "description" : "" , "main" : "index.js" , "scripts" : { "test" : "echo \"Error: no test specified\" && exit 1" }, "keywords" : [], "author" : "" , "license" : "ISC" }
此时,我们还需要把此处的 ES6 语法的代码转换成 ES5 才能执行,所以需要一个转换的插件(例如 webpack)。这里我们使用 Babel 进行转换。全局安装 Babel:
1 2 3 4 npm install -g babel-cli 此外,还需要安装以下插件 npm install --save-dev babel-preset-es2015 babel-cli
安装完成后,package.json 文件中多了以下内容:
1 2 3 4 "devDependencies": { "babel-cli": "^6.26.0", "babel-preset-es2015": "^6.24.1" }
在根目录下创建 .babelrc 文件,并输入一下内容:
1 2 3 4 5 6 { "presets" : [ "es2015" ], "plugins" : [] }
最后就可以执行转换命令把 es6 的代码转换成 es5 的代码:
1 babel src/index.js -o dist/index.js
执行完成后,dist/index.js 文件的内容为(转换成了es5的写法):
1 2 3 4 "use strict" ;var a = 1 ;console .log(a);
可以配置 npm 命令来简化转换操作,修改 package.json 文件,添加如下内容:
1 2 3 "scripts": { "build": "babel src/index.js -o dist/index.js" },
此时,执行 npm run build 命令就可以进行打包。
变量声明 1 2 3 4 声明方式: var 全局声明 let 局部声明 const 常量
例子:
1 2 3 4 5 6 7 var a = "wyzane" ;{ var a = "wz" ; } console .log(a);
1 2 3 4 5 6 7 var a = "wyzane" ;{ let a = "wz" ; } console .log(a);
1 2 3 4 5 6 7 let a = "wyzane" ;{ let a = "wz" ; } console .log(a);
1 2 3 4 5 6 7 let a = "wyzane" ;{ a = "wz" ; } console .log(a);
1 2 3 4 5 { let a = "wz" ; } console .log(a);
使用 var 时,数据容易被污染
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 for (var i=0 ; i<10 ; i++) { console .log("inner: " + i); } console .log("outer: " + i);
使用 let 时:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 for (let i=0 ; i<10 ; i++) { console .log("inner: " + i); } console .log("outer: " + i);
变量解构赋值 数组解构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 let [a, b, c] = [1 , 2 , 3 ];console .log(a);解构的时候定义默认值: let [a, b, c=5 ] = [1 , 2 ];console .log(a); console .log(c); let [a=0 , b, c] = [1 , 2 ];console .log(a); console .log(c); let [a, b, c=6 ] = [1 , 2 , undefined ];console .log(a); console .log(c); let [a, b, c=6 ] = [1 , 2 , null ];console .log(a); console .log(c);
对象解构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 对象的解构是根据属性名称进行对应的 let {name1, name2} = {'name2' : 'wyzane' , 'name1' : 'wz' };console .log(name1); console .log(name2); 一个小坑: let foo;{foo} = {foo : 'wyzane' }; console .log(foo);上面的解构方式会报错,应该使用下面的方式: let foo;({foo} = {foo : 'wyzane' }); console .log(foo);
字符串解构:
1 2 3 let [a, b, c] = 'nihao' ;console .log(a); console .log(c);
对象扩展运算符 对象扩展运算符使用 … 表示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 function test (...args ) { console .log(args[0 ]); console .log(args[1 ]); console .log(args[2 ]); console .log(args[3 ]); } test(1 , 2 , 3 ); let a1 = ['1' , '2' , '3' ];let a2 = a1;console .log(a1); a2.push('4' ); console .log(a1); let a1 = ['1' , '2' , '3' ];let a2 = [...a1];console .log(a1); a2.push('4' ); console .log(a1);
rest运算符 与对象扩展运算符类似
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 function test (f, ...args ) { console .log(args.length); console .log(args[0 ]); for (let i=0 ; i<args.length; i++) { console .log(args[i]); } for (let val of args) { console .log(val); } } test(0 , 1 , 2 , 3 , 4 , 5 , 6 );
字符串操作 创建一个node项目的步骤:
1 2 1. 执行 npm init 初始化项目 2. 执行 cnpm install -g live-server 安装live-server作为前端服务器
字符串模板的使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 let name = 'wyuzane' ;let info = '你们好呀,我是' + name + ',欢迎来到学习园地' ;let info = `你们好呀,我是${name} ,欢迎来到学习园地` ;let info = `你们好呀,我是${name} ,<br>欢迎来到学习园地` ;document .write(info);let a = 1 ;let b = 2 ;let c = `${a+b} ` ;document .write(c);let name = 'wyzane' ;let info = '你们好呀,我是wyzane,欢迎来到学习园地' ;document .write(info.indexOf(name)); document .write(info.includes(name)); document .write('wyzane | ' .repeat(3 ));
数字操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 let binary = 0B010101 ;console .log(binary); let octal = 0O666 ;console .log(octal); let a = 11 /4 ;console .log(Number .isFinite(a)); console .log(Number .isFinite(NaN )); console .log(Number .isFinite('wyzane' )); console .log(Number .isNaN(NaN )); console .log(Number .isNaN('wyzane' )); let a = 1.1 ;let b = 2 ;console .log(Number .isInteger(a)); console .log(Number .isInteger(b)); let a = 2.531 ;let b = 2 ;console .log(Number .parseInt(a)); console .log(Number .parseFloat(b)); console .log(Number .MAX_SAFE_INTEGER); console .log(Math .pow(2 , 53 ) - 1 ); console .log(Number .MIN_SAFE_INTEGER); console .log(Number .isSafeInteger(123 ));
数组1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 let json = { '0' : 'wyzane1' , '1' : 'wyzane2' , '2' : 'wyzane3' , length: 3 } let arr = Array .from(json);console .log(arr); let arr = Array .of(3 ,4 ,5 ,6 );console .log(arr); let arr = Array .of('qw' , 'er' , 'rt' );console .log(arr); let a = '[3, 4, 5, 6]' ;console .log(eval (a)); find(function (val, idx, arr ) { return val > 5 ; }) let arr = [1 , 2 , 3 , 4 , 5 ];console .log(arr.find(function (val, index, arr ) { return val > 3 ; })); let arr = ['wyzane' , 'nihao' , 'hello' ];console .log(arr.find(function (val, index, arr ) { return val == 'hello' ; })); let arr = ['wyzane' , 'nihao' , 'hello' ];console .log(arr.find(function (val, index, arr ) { return val == 'he' ; }));
数组2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 let arr = ['1' , '2' , '3' , '4' , '5' ];arr.fill('wyzane' , 1 , 4 ); console .log(arr); let arr = ['1' , '2' , '3' , '4' , '5' ];for (let val of arr) { console .log(val); } for (let val of arr.keys()) { console .log(val); } for (let val of arr.entries()) { console .log(val); } for (let [idx, val] of arr.entries()) { console .log(val); console .log(idx); } let arr = ['1' , '2' , '3' , '4' , '5' ];let arr2 = arr.entries()console .log(arr2); console .log(arr2.next().value); let json = ['hello' , 'nihao' , 'hihi' ]json.forEach((idx, val ) => console .log(idx, val)); let json = ['hello' , 'nihao' , 'hihi' ]json.filter(x => console .log(x)); let json = ['hello' , 'nihao' , 'hihi' ]json.some(x => console .log(x)); let json = ['hello' , 'nihao' , 'hihi' ]console .log(json.map(x => 'web' )); let json = ['hello' , 'nihao' , 'hihi' ]console .log(json.toString()); let json = ['hello' , 'nihao' , 'hihi' ]console .log(json.join('|' ));
函数的扩展 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 function add (a, b ) { console .log(a + b); } add(1 , 2 ); function add (a, b=4 ) { console .log(a + b); } add(1 ); function add (a, b=4 ) { if (a==0 ) { throw new Error ('a ia error' ); } console .log(a + b); } add(0 ); function add (a, b=4 ) { console .log(a + b); } function add2 (a, b ) { console .log(a + b); } console .log(add.length); console .log(add2.length); let add = (a, b=1 ) => a + b;console .log(add(1 )); let add = (a, b=1 ) => { console .log('wyzane' ); return a + b; } console .log(add(1 )); let json = { a: 'wyzane1' , b: 'wyzane2' } function func ({a, b='nihao' } ) { console .log(a, b); } func(json); let json = ['nihao' , 'hi' , 'hello' ];function func ([a, b, c] ) { console .log(a, b, c); } func(json); let json = ['nihao' , 'hi' , 'hello' ];function func (a, b, c ) { console .log(a, b, c); } func(...json); let json = { a: 'nihao' , b: 'hi' } console .log('a' in json);
对象 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 let name = 'wyzane' ;let age = 18 ;let wz = {name : name, age : age};console .log(wz); let name = 'wyzane' ;let age = 18 ;let wz = {name, age};console .log(wz); let key = 'name' ;let wz = { [key]: 'wyzane' } console .log(wz); let wz = { add: function (a, b ) { return a + b; } } console .log(wz.add(1 , 2 )); let obj1 = {name : 'wyzane' };let obj2 = {name : 'wyzane' };console .log(obj1.name === obj2.name); console .log(Object .is(obj1.name, obj2.name)); console .log(+0 === -0 ); console .log(NaN === NaN ); console .log(Object .is(+0 , -0 )); console .log(Object .is(NaN , NaN )); let a = {name : 'wyzane' }let b = {age : 18 }let c = {salary : 1 }let d = Object .assign(a, b, c);console .log(d);
symbol在对象中的作用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 let a = new String ;let b = new Array ;let c = new Number ;let d = new Boolean ;let e = new Object ;let f = Symbol ();console .log(typeof (f)); let a = Symbol ('wyzane' );console .log(a); console .log(a.toString()); let name = Symbol ();let obj = { [name]: 'wyzane' } console .log(obj.name); console .log(obj[name]); obj[name] = 'wz' console .log(obj[name]); let person = {name : 'wyzane' , skill : 'web' }let age = Symbol ()person[age] = 18 console .log(person); for (let item in person) { console .log(person[item]); }
Set与WeakSet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 let setArr = new Set (['wyzane1' , 'wyzane2' , 'wyzane' ]);console .log(setArr); setArr.add('nihao' ); console .log(setArr); console .log(setArr.has('wyzane' )); setArr.delete('wyzane' ); setArr.clear(); for (let item of setArr) { console .log(item); } setArr.forEach((val ) => console .log(val)); console .log(setArr.size);
1 2 3 4 5 6 let setArr = new WeakSet ();let obj = {name : 'wyzane1' , age : 13 };setArr.add(obj); console .log(setArr);
map数据结构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 let json = { name: 'wyzane' , age: 12 } let map = new Map ();map.set(json, 'im' ); map.set('salary' , 13 ); console .log(map); console .log(map.get('salary' )); map.delete(json); map.clear(); map.size; map.has(json);
proxy的使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 let obj = { add: function (val ) { return val + 100 ; }, name: 'wyzane' } console .log(obj.add(100 )); console .log(obj.name); let obj = new Proxy ({ add: function (val ) { return val + 100 ; }, name: 'wyzane' }, { get : function(target, key, property){ console .log("预处理" ); } }) console .log(obj.name); let obj = new Proxy ({ add: function (val ) { return val + 100 ; }, name: 'wyzane' }, { get : function(target, key, property){ console .log("预处理" ); console .log(target); return target[key]; } }) console .log(obj.name); let obj = new Proxy ({ add: function (val ) { return val + 100 ; }, name: 'wyzane' }, { get : function(target, key, property){ console .log("预处理" ); console .log(target); return target[key]; }, set : function(target, key, value, receiver) { console .log(`setting ${key} = ${value} ` ); target[key] = value; } }) console .log(obj.name);obj.name = 'nihao' ; console .log(obj.name); let target = function ( ) { return 'nihao' ; } let handler = { apply(target, ctx, args) { console .log('apply func' ); } } let obj = new Proxy (target, handler);console .log(obj()); let target = function ( ) { return 'nihao' ; } let handler = { apply(target, ctx, args) { console .log('apply func' ); return Reflect .apply(...arguments); } } let obj = new Proxy (target, handler);console .log(obj());
async与await的使用 async与await应该算是 ES7 中的语法,下面介绍下它的使用。
1 2 async 可以使一个方法变为异步方法 await 用于获取一个异步方法中的返回值,可以等待异步方法的执行完成并返回(await需要在异步方法中使用)
简单例子:
1 2 3 4 5 async function getData ( ) { return '你好' ; } console .log(getData());
可以看到,async方法返回的是一个 Promise 对象,想要获取函数的返回值,可以使用下面的方式:
方式一:使用 then 方法
1 2 3 4 5 6 7 8 9 async function getData ( ) { return '你好' ; } let p = getData();p.then((data )=> { console .log(data); })
方式二:使用 await ,await只能在异步方法中使用
1 2 3 4 5 6 7 8 9 10 async function getData ( ) { return '你好' ; } async function test ( ) { let ret = await getData(); console .log(ret); } test()
Promise的使用 Promise 是异步编程的一种解决方案,我们可以把将来发生的事件定义到 Promise 中。
下面是 Promise 使用的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 let state = 1 ;let step1 = function (resolve, reject ) { console .log('1-开始洗菜做饭' ); if (state == 1 ){ resolve('洗菜做饭-完成' ); }else { reject('洗菜做饭-出错' ); } } let step2 = function (resolve, reject ) { console .log('2.吃饭' ); if (state==1 ){ resolve('吃饭-完成' ); }else { reject('吃饭-出错' ); } } let step3 = function (resolve, reject ) { console .log('3.洗碗' ); if (state==1 ) { resolve('洗碗-完成' ); }else { reject('洗碗-出错' ); } } new Promise (step1).then(function (val ) { console .log(val); return new Promise (step2); }).then(function (val ) { console .log(val); return new Promise (step3); }).then(function (val ) { console .log(val); }); let state = 1 ;let step1 = function (resolve, reject ) { console .log('1-开始洗菜做饭' ); if (state == 1 ){ resolve('洗菜做饭-完成' ); }else { reject('洗菜做饭-出错' ); } } let step2 = function (resolve, reject ) { state = 0 ; console .log('2.吃饭' ); if (state==1 ){ resolve('吃饭-完成' ); }else { reject('吃饭-出错' ); } } let step3 = function (resolve, reject ) { console .log('3.洗碗' ); if (state==1 ) { resolve('洗碗-完成' ); }else { reject('洗碗-出错' ); } } new Promise (step1).then(function (val ) { console .log(val); return new Promise (step2); }).then(function (val ) { console .log(val); return new Promise (step3); }).then(function (val ) { console .log(val); });
还可以在 async 方法中调用含有 Promise 的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 function getData ( ) { return new Promise ((resolve, reject )=> { setTimeout(() => { let username = 'zhangsan' ; resolve(username); }, 1000 ) }) } async function test ( ) { let ret = await getData(); console .log(ret); } test()
es6中类的使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 class Coder { name (val) { console .log(val); } skill (val) { console .log(val); } } let wyzane = new Coder; wyzane.name('nihao' ); wyzane.skill('nihaoya' ); class Coder { name (val) { console .log('name method is called' ); console .log(val); } skill (val) { this .name(val) } } let wyzane = new Coder;wyzane.name('nihao' ); class Person { constructor (name, age) { this ._name = name; this ._age = age; } run () { console .log(this ._name); } static work () { console .log('静态方法' ); } } let person = new Person('zhangsan' , 20 );person.run(); Person.work(); class Xiaoming extends Person { constructor (name, age, gender) { super (name, age); this .gender = gender; } eat () { console .log('小明喜欢吃糖' ); } } let xm = new Xiaoming('xiaoming' , 20 , '男' );xm.run() xm.eat(); Xiaoming.work() class Client { constructor () { console .log('执行构造方法' ); } static getInstance () { if (!Client.instance) { Client.instance = new Client(); } return Client.instance } }; let client1 = Client.getInstance();let client2 = Client.getInstance();
作为对比,es5中类的定义如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 function Person (name, age ) { this .name = name; this .age = age; this .run = function ( ) { console .log(this .name); } } Person.prototype.gender = '男' ; Person.prototype.work = function ( ) { console .log(this .name); } Person.setName = function ( ) { console .log('静态方法' ); } var p = new Person('zhansan' , 20 ); p.run(); p.work(); Person.setName(); function Web (name, age ) { Person.call(this , name, age); } Web.prototype = new Person(); var web = Web('lisi' , 20 );web.run();
模块化操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 temp.js: export let name = 'wyzane' ;index.js: import {name} from './temp' console .log(name);let a = 'a' ;let b = 'b' ;let c = 'c' ;export {a, b, c};export function add (a, b ) { return a + b; } let a = 'a' ;let b = 'b' ;let c = 'c' ;export { name as a, cname as b, skill as c } temp.js: export default var a = 'nihao' ;index.js import 自定义名称 from './temp'