偶然在项目中看见,感觉是重要的内容,先了解下基本语法,等有空再深入学习。 babel迷之安装 一觉醒来打开webstorm发现装上了Σ(っ °Д °;)っ File Watcher打开添加babel时programa一栏填写:
$ProjectFileDir$/node_modules/.bin/babel
然后就能自动转码为ES5啦:)
1. 文档转换 Babel的REPL在线编译器,将ES6代码转为ES5代码。https://babeljs.io/repl/
2. ES6部分特性
var
声明的内层变量会覆盖外层变量,而let
提供块级作用域,变量只在代码块内有效。
当引用第三方库时声明的变量,用const
来声明可以避免未来不小心重命名而导致出现bug
引入Class
(类)概念,可以通过extends
关键字实现继承。(这部分感觉有点像java)
arrow function箭头函数的
this是继承外层代码块的
this`。
template string
,用反引号来标识起始,用${}
来引用变量,而且所有的空格和缩进都会被保留在输出之中.
destructuring
解构:从数组和对象中提取值,对变量进行赋值。
default
默认值, rest
语法(用Rest操作符以后,args参数就是一个数组了,任何操作数组的方法都可以直接对args使用)
电脑重装了,反正要重新配置环境,不如找个东西边学边装。就决定是你了,ES6!
惯例安装nodejs以及express
1 2 3 4 5 $ npm install express --save $ npm install body-parser --save $ npm install cookie-parser --save $ npm install multer --save $ npm list express
途中出现第一个问题,npm ERR! extraneous
,https://github.com/npm/npm/issues/10004#issuecomment-210710935,快捷方法是重装nodejs后用管理员模式安装>_o 第二个问题 express command not found
,解决方法https://stackoverflow.com/questions/23002448/express-command-not-found 1 npm install -g express-generator
gulp文档 1 2 3 $ touch .babelrc $ touch gulpfile.babel.js
因为使用ES6语法,所以必须创建gulpfile.babel.js
文件而不是gulpfile.js
然后又出现了很多问题,我就先去学习了gulp的详细用法,写了三篇文章总结。又学会了使用yeoman工具直接构建项目骨架。详细参见之前的博文。我发现webstorm里也可以直接选择yeoman构建,神器啊。 下面真的开始学习ES6语法了 O_<
参考阮一峰的《ECMAScript 6 入门》
1. let & const 1 2 3 4 5 6 7 function test ( ) { for (let i=1 ;i<3 ;i++){ console .log(i); } console .log(i); } test();
块作用域(大括号内)第二个console.log(i)
脱离了块作用域,于是只能输出1,2。
严格模式:ES5代码中存在use strict
来启动文件采用严格模式,ES6中则强制开启。严格模式中变量未声明则不能引用,会报错。
使用let时不能重复定义变量。
使用const声明的常量不能修改。
第4点注意情况
1 2 3 4 5 6 const PI =3.1415926 ; const K ={ a:1 } K.b = 3 ;
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 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 97 { let a,b,rest; [a,b]=[1 ,2 ]; console .log(a,b); } { let a,b,rest; [a,b,...rest]=[1 ,2 ,3 ,4 ,5 ,6 ]; console .log(a,b,rest); } { let a,b; ({a,b}={a :1 ,b :2 }) console .log(a,b); } { let a,b,c,rest; [a,b]=[1 ,2 ] console .log(a,b,c); } { let a,b,c,rest; [a,b,c=3 ]=[1 ,2 ] console .log(a,b,c); } { let a=1 ; let b=2 ; [a,b]=[b,a]; console .log(a,b); } { function f ( ) { return [1 ,2 ]; } let a,b; [a,b]=f(); console .log(a,b); } { function f ( ) { return [1 ,2 ,3 ,4 ,5 ]; } let a,b,c; [a,,,b]=f(); console .log(a,b); } { function f ( ) { return [1 ,2 ,3 ,4 ,5 ]; } let a,b,c; [a,...b]=f(); console .log(a,b); } { function f ( ) { return [1 ,2 ,3 ,4 ,5 ]; } let a,b,c; [a,,...b]=f(); console .log(a,b); } { let o= {p :42 ,q :true }; let {p,q}=o; console .log(p,q); } { let {a=10 ,b=5 }={a :3 }; console .log(a,b); } { let metaData ={ title:'abc' , test:[{ title:'test' , desc:'description' }] } let {title :esTitle,test :[{title :cnTitle}]}=metaData; console .log(esTitle,cnTitle); }
3. 正则扩展 TBC
4. 字符串扩展 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 { console .log('a' ,'\u0061' ); console .log('s' ,'\u20BB7' ); console .log('s' ,'\u{20BB7}' ); } { let s = '𠮷' ; console .log('length' ,s.length); console .log('0' ,s.charAt(0 )); console .log('1' ,s.charAt(1 )); console .log('at0' ,s.charCodeAt(0 )); console .log('at1' ,s.charCodeAt(1 )); let s1 = '𠮷a' ; console .log('length' ,s1.length); console .log('code0' ,s1.codePointAt(0 )); console .log('code0' ,s1.codePointAt(0 ).toString(16 )); console .log('code1' ,s1.codePointAt(1 )); console .log('code2' ,s1.codePointAt(2 )); } { console .log(String .fromCharCode('0x20BB7' )); console .log(String .fromCodePoint('0x20BB7' )); } { let str ='\u{20BB7}abc' ; for (let i=0 ;i<str.length;i++){ console .log('es5' ,str[i]); } for (let code of str){ console .log('es6' ,code); } } { let str='string' ; console .log('includes' ,str.includes("r" )); console .log('start' ,str.startsWith('str' )); console .log('end' ,str.endsWith('ing' )); } { let str='abc' ; console .log(str.repeat(2 )); } { let name ='list' ; let info = 'hello world' ; let m = `I am ${name} ,${info} ` ; console .log(m); } { console .log('1' .padStart(2 ,'0' )); console .log('1' .padEnd(2 ,'0' )); } { let user = { name:'list' , info:'hello world' }; console .log(abc`i am ${user.name} ,${user.info} ` ); function abc (s,v1,v2 ) { console .log(s,v1,v2); return s+v1+v2; } } { console .log(String .raw`Hi\n${1 +2 } ` ); console .log(`Hi\n${1 +2 } ` ); }
5. 数值扩展 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 { console .log(0b111110111 ); console .log(0o767 ); } { console .log('15' ,Number .isFinite(15 )); console .log('NaN' ,Number .isFinite(NaN )); console .log('1/0' ,Number .isFinite('true' /0 )); console .log('NaN' ,Number .isNaN(NaN )); console .log('NaN' ,Number .isNaN(0 )); } { console .log('25' ,Number .isInteger(25 )); console .log('25.0' ,Number .isInteger(25.0 )); console .log('25.1' ,Number .isInteger(25.1 )); console .log('25' ,Number .isInteger('25' )); } { console .log(Number .MAX_SAFE_INTEGER); console .log(Number .MIN_SAFE_INTEGER); console .log('10' ,Number .isSafeInteger(10 )); console .log('a' ,Number .isSafeInteger('a' )); } { console .log(4.1 ,Math .trunc(4.1 )); console .log(4.9 ,Math .trunc(4.9 )); } { console .log('-5' ,Math .sign(-5 )); console .log('0' ,Math .sign(0 )); console .log('5' ,Math .sign(5 )); console .log('50' ,Math .sign('50' )); console .log('foo' ,Math .sign('foo' )); } { console .log('-1' ,Math .cbrt(-1 )); console .log('8' ,Math .cbrt(8 )); }
6.数组扩展 问题:.values is not a function
解决:Uncaught TypeError: Object.values is not a function JavaScript MDN文档Object.values() 需要import babel-polyfill
,否则不兼容。
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 { let arr = Array .of(3 ,4 ,7 ,9 ,11 ); console .log('arr=' ,arr); let empty = Array .of(); console .log('empty=' ,empty); } { let p = document .querySelectorAll('p' ); let pArr = Array .from(p); pArr.forEach(function (item ) { console .log(item.textContent); }); console .log(Array .from([1 ,3 ,5 ],function (item ) {return item*2 ;})); } { console .log('fill-7' ,[1 ,'a' ,undefined ].fill(7 )); console .log('fill,pos' ,['a' ,'b' ,'c' ].fill(7 ,1 ,3 )); } { for (let index of ['1' ,'c' ,'ks' ].keys()){ console .log('keys' ,index); } for (let value of ['1' ,'c' ,'ks' ].entries()){ console .log('entries' ,value); } for (let [index,value] of ['1' ,'c' ,'ks' ].entries()){ console .log('entries' ,index,value); } } { console .log([1 ,2 ,3 ,4 ,5 ].copyWithin(0 ,3 ,4 )); } { console .log([1 ,2 ,3 ,4 ,5 ,6 ].find(function (item ) {return item>3 })); console .log([1 ,2 ,3 ,4 ,5 ,6 ].findIndex(function (item ) {return item>3 })); } { console .log('number' ,[1 ,2 ,NaN ].includes(1 )); }
7. 函数扩展 函数新增特性:参数默认值;rest参数;扩展运算符;箭头函数;this绑定;尾调用。
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 { function test (x,y = 'world' ) { console .log('默认值' ,x,y); } test('hello' ); test('hello' ,'u' ); } { let x = 'test' ; function test2 (x,y=x ) { console .log('作用域' ,x,y); } test2('cute' ); test2(); } { let x = 'test' ; function test2 (c,y=x ) { console .log('作用域' ,c,y); } test2('cute' ); } { function test3 (...arg ) { for (let v of arg){ console .log('rest' ,v); } } test3(1 ,2 ,3 ,4 ,'a' ); } { console .log(...[1 ,2 ,3 ]); console .log('a' ,...[1 ,2 ,3 ]); } { let arrow = v => v*2 ; let arrow2 = () =>5 ; console .log(arrow(3 )); console .log(arrow2()); } { function tail (x ) { console .log('tail' ,x); } function fx (x ) { return tail(x); } fx(123 ); }
8. 对象扩展 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 o = 1 ; let k = 2 ; let es5 = { o: o, k: k }; let es6 = { o, k }; console .log(es5,es6); let es5_method = { hello: function ( ) { console .log('hello' ); } }; let es6_method = { hello(){ console .log('hello' ); } }; console .log(es5_method.hello(),es6_method.hello()); } { let a = 'b' ; let es5_obj = { a:'c' , b:'c' }; let es6_obj = { [a]:'c' }; console .log(es5_obj,es6_obj); } { console .log('字符串' ,Object .is('abc' ,'abc' ),'abc' ==='abc' ); console .log('数组' ,Object .is([],[]),[]===[]); } { console .log('拷贝' ,Object .assign({a :'a' },{b :'b' })); } { let test = {k :123 ,o :456 }; for (let [key,value] of Object .entries(test)){ console .log([key,value]); } }
9. 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 { let a1=Symbol (); let a2=Symbol (); console .log(a1===a2); let a3 = Symbol .for('a3' ); let a4 = Symbol .for('a3' ); console .log(a3===a4); } { let a1 = Symbol .for('abc' ); let obj = { [a1]:'123' , 'abc' :345 , 'c' :456 }; console .log('obj' ,obj); for (let [key,value] of Object .entries(obj)){ console .log('let of' ,key,value); } Object .getOwnPropertySymbols(obj).forEach(function (item ) { console .log(obj[item]); }) Reflect .ownKeys(obj).forEach(function (item ) { console .log('ownKeys' ,item,obj[item]); }) }
10. set-map数据结构 优先使用map,对数据要求高用set。
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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 { let list = new Set (); list.add(5 ); list.add(7 ); console .log('size' ,list.size); } { let arr = [1 ,2 ,3 ,4 ,5 ]; let list = new Set (arr); console .log('size' ,list.size); } { let list = new Set (); list.add(1 ); list.add(2 ); list.add(1 ); console .log('list' ,list); let arr = [1 ,2 ,3 ,1 ,2 ]; let list2 =new Set (arr); console .log('list2' ,list2); let arr2 = [1 ,2 ,3 ,1 ,'2' ]; let list3 =new Set (arr2); console .log('list3' ,list3); } { let arr = ['add' ,'delete' ,'clear' ,'has' ]; let list = new Set (arr); console .log('has' ,list.has('add' )); console .log('delete' ,list.delete('add' ),list); list.clear(); console .log('list' ,list); } { let arr = ['add' ,'delete' ,'clear' ,'has' ]; let list = new Set (arr); for (let key of list.keys()){ console .log('keys' ,key); } for (let value of list.values()){ console .log('value' ,value); } for (let value of list){ console .log('value' ,value); } for (let [key,value] of list.entries()){ console .log('entries' ,key,value); } list.forEach(function (item ) { console .log(item); }) } { let weakList = new WeakSet (); let arg = {}; weakList.add(arg); console .log('weakList' ,weakList); } { let map = new Map (); let arr = ['123' ]; map.set(arr,456 ); console .log('map' ,map,map.get(arr)); } { let map = new Map ([['a' ,123 ],['b' ,456 ]]); console .log('map args' ,map); console .log('size' ,map.size); console .log('delete' ,map.delete('a' ),map); console .log('clear' ,map.clear(),map); } { let weakmap = new WeakMap (); let o ={}; weakmap.set(o,123 ); console .log(weakmap.get(o)); } { let map = new Map (); let array = []; map.set('t' ,1 ); array.push({t :1 }); console .info('map array' ,map,array); let map_exist = map.has('t' ); let array_exist = array.find(item => item.t); console .info('map-array' ,map_exist,array_exist); map.set('t' ,2 ); array.forEach(item => item.t?item.t=2 :'' ); console .info('map-array-modify' ,map,array); map.delete('t' ); let index = array.findIndex(item => item.t); array.splice(index,1 ); console .info('map array-empty' ,map,array); } { let set = new Set (); let array = []; set.add({t :1 }); array.push({t :1 }); console .info('set-array' ,set,array); let set_exist = set.has({t :1 }); let array_exist = array.find(item => item.t); console .info('set-array' ,set_exist,array_exist); set.forEach(item => item.t?item.t=2 :'' ); array.forEach(item => item.t?item.t=2 :'' ); console .info('set-array-modify' ,set,array); set.forEach(item => item.t?set.delete(item):'' ); let index = array.findIndex(item => item.t); array.splice(index,1 ); console .info('set-array-empty' ,set,array); } { let item ={t :1 }; let map = new Map (); let set =new Set (); let obj = {}; map.set('t' ,1 ); set.add(item); obj['t' ]= 1 ; console .info('obj-map-set' ,obj,map,set); console .info({ map_exist:map.has('t' ), set_exist:set.has(item), obj_exist:'t' in obj }); map.set('t' ,2 ); item.t =2 ; obj['t' ]= 2 ; console .info('obj-map-set-modify' ,obj,map,set); map.delete('t' ); set.delete(item); delete obj['t' ]; console .info('obj-map-set-empty' ,obj,map,set); }
11. Proxy和Reflect 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 { let obj = { time:'2017-11-17' , name:'net' , _r:123 }; let monitor = new Proxy (obj,{ get(target,key){ return target[key].replace('2017' ,'2018' ); }, set(target,key,value){ if (key==='name' ){ return target[key]=value; }else { return target[key]; } }, has(target,key){ if (key==='name' ){ return target[key]; }else { return false ; } }, deleteProperty(target,key){ if (key.indexOf('_' )>-1 ){ delete target[key]; return true ; }else { return target[key]; } }, ownKeys(target){ return Object .keys(target).filter(item => item!='time' ) } }); console .log('get' ,monitor.time); monitor.name ='new name' ; console .log('set' ,monitor.time,monitor.name); console .log('has' ,'name' in monitor,'time' in monitor); console .log('ownKeys' ,Object .keys(monitor)); } { let obj = { time:'2017-11-17' , name:'net' , _r:123 }; console .log('Reflect get' ,Reflect .get(obj,'time' )); Reflect .set(obj,'name' ,'new name' ); console .log(obj); console .log('has' ,Reflect .has(obj,'name' )); } { function validator (target,validator ) { return new Proxy (target,{ _validator:validator, set(target,key,value,proxy){ if (target.hasOwnProperty(key)){ let va = this ._validator[key]; if (!!va(value)){ return Reflect .set(target,key,value,proxy); }else { throw Error (`不能设置${key} 到${value} ` ); } }else { throw Error (`${key} 不存在` ); } } }); } const personValidators ={ name(val){ return typeof val === 'string' ; }, age(val){ return typeof val === 'number' && val >18 ; } }; class Person { constructor (name,age){ this .name = name; this .age =age; return validator(this ,personValidators); } } const person = new Person('lilei' ,30 ); console .info(person); person.name ='Han mei mei' ; console .info(person); }
12. 类和对象 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 { class Parent { constructor (name = 'qq') { this .name = name; } } let v_parent = new Parent('v' ); console .log('构造函数和实例' , v_parent); } { class Parent { constructor (name = 'qq') { this .name = name; } } class Child extends Parent { } console .log('继承' , new Child()); } { class Parent { constructor (name = 'qq') { this .name = name; } } class Child extends Parent { constructor (name = 'child') { super (name); this .type = 'child' ; } } console .log('继承传递参数' , new Child('hello' )); } { class Parent { constructor (name = 'qq') { this .name = name; } get longName() { return 'mk' + this .name; } set longName(value) { this .name = value; } } let v = new Parent(); console .log('getter' , v.longName); v.longName = 'hello' ; console .log('setter' , v.longName); } { class Parent { constructor (name = 'qq') { this .name = name; } static tell() { console .log('tell' ); } } Parent.tell(); } { class Parent { constructor (name = 'qq') { this .name = name; } static tell() { console .log('tell' ); } } Parent.type = 'test' ; console .log('静态属性' , Parent.type); }
13. 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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 { let ajax = function (callback ) { console .log('execute' ); setTimeout(function ( ) { callback && callback.call() }, 1000 ); }; ajax(function ( ) { console .log('timeout1' ); }); } { let ajax = function ( ) { console .log('execute2' ); return new Promise (function (resolve, reject ) { setTimeout(function ( ) { resolve() }, 1000 ); }); }; ajax().then(function ( ) { console .log('promise' , 'timeout2' ); }) } { let ajax = function ( ) { console .log('execute3' ); return new Promise (function (resolve, reject ) { setTimeout(function ( ) { resolve() }, 1000 ); }); }; ajax() .then(function ( ) { return new Promise (function (resolve, reject ) { setTimeout(function ( ) { resolve() }, 2000 ); }); }) .then(function ( ) { console .log('timeout3' ); }) } { let ajax = function (num ) { console .log('execute4' ); return new Promise (function (resolve, reject ) { if (num > 5 ) { resolve(); } else { throw new Error ('error!' ); } }); }; ajax(6 ).then(function ( ) { console .log('log' , 6 ); }).catch(function (err ) { console .log('catch' , err); }) ajax(3 ).then(function ( ) { console .log('log' , 3 ); }).catch(function (err ) { console .log('catch' , err); }) } { function loadImage (src ) { return new Promise ((resolve, reject ) => { let img = document .createElement('img' ); img.src = src; img.onload = function ( ) { resolve(img); } img.onerror = function (err ) { reject(err); } }); } function showImage (imgs ) { imgs.forEach(function (img ) { document .body.appendChild(img); }) } Promise .all([ loadImage('http://wx2.sinaimg.cn/mw690/6e67f96fgy1fkgeowvnqkj205606yjrh.jpg' ), loadImage('http://wx2.sinaimg.cn/mw690/6e67f96fgy1fkgeowvnqkj205606yjrh.jpg' ), loadImage('http://wx2.sinaimg.cn/mw690/6e67f96fgy1fkgeowvnqkj205606yjrh.jpg' ) ]).then(showImage) } { function loadImage (src ) { return new Promise ((resolve, reject ) => { let img = document .createElement('img' ); img.src = src; img.onload = function ( ) { resolve(img); } img.onerror = function (err ) { reject(err); } }); } function showImage (img ) { let p = document .createElement('p' ); p.appendChild(img); document .body.appendChild(p); } Promise .race([ loadImage('http://wx2.sinaimg.cn/mw690/6e67f96fgy1fkgeowvnqkj205606yjrh.jpg' ), loadImage('http://wx2.sinaimg.cn/mw690/6e67f96fgy1fkgeowvnqkj205606yjrh.jpg' ), loadImage('http://wx2.sinaimg.cn/mw690/6e67f96fgy1fkgeowvnqkj205606yjrh.jpg' ) ]).then(showImage) }
14. Iterator 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 { let arr = ['hello' , 'world' ]; let map = arr[Symbol .iterator](); console .log(map.next()); console .log(map.next()); console .log(map.next()); } { let obj = { start: [1 , 3 , 2 ], end: [7 , 9 , 8 ], [Symbol .iterator]() { let self = this ; let index = 0 ; let arr = self.start.concat(self.end); let len = arr.length; return { next() { if (index < len) { return { value: arr[index++], done: false }; } else { return { value: arr[index++], done: true }; } } }; } }; for (let key of obj) { console .log(key); } } { let arr = ['hello' , 'world' ]; for (let value of arr) { console .log('value' , value); } }
15. Genertor 报错:regeneratorRuntime is not defined
解决:transform-runtime ,可以选择性加载babel插件。
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 97 98 99 100 101 102 103 104 105 106 107 108 109 { let tell = function *( ) { yield 'a' ; yield 'b' ; return 'c' }; let k = tell(); console .log(k.next()); console .log(k.next()); console .log(k.next()); console .log(k.next()); } { let obj = {}; obj[Symbol .iterator] = function *( ) { yield 1 ; yield 2 ; yield 3 ; } for (let value of obj) { console .log('value' , value); } } { let draw = function (count ) { console .info(`剩余${count} 次` ); }; let residue = function *(count ) { while (count > 0 ) { count--; yield draw(count); } } let star = residue(5 ); let btn = document .createElement('button' ); btn.id = 'start' ; btn.textContent = '抽奖' ; document .body.appendChild(btn); document .getElementById('start' ).addEventListener('click' , function ( ) { star.next(); }, false ); } { let ajax = function *( ) { yield new Promise (function (resolve, reject ) { setTimeout(function ( ) { resolve({ code: 0 }) }, 200 ); }); } let pull = function ( ) { let generator = ajax(); let step = generator.next(); step.value.then(function (d ) { if (d.code != 0 ) { setTimeout(function ( ) { console .info('wait' ); pull() }, 1000 ); } else { console .info(d); } }) } pull(); }
16. Decorators 修饰器是一个函数用来修改类的行为。
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 { let readonly = function (target, name, descriptor ) { descriptor.writable = false ; return descriptor }; class Test { @readonly time() { return '2017-03-11' } } let test = new Test(); console .log(test.time()); } { let typename = function (target, name, descriptor ) { target.myname = 'hello' ; } @typename class Test { } console .log('类修饰符' , Test.myname); }
17. 模块化 18. 问题 描述:当使用import导入模块时,出现exports is not defined
1 2 3 4 5 6 7 //1、安装插件 npm install --save-dev babel-plugin-transform-es2015-modules-umd //2、设置.babelrc配置文件 { "plugins": ["transform-es2015-modules-umd"] }