es6标准入门
async 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 (async (){ function promisefn (url ) { return Promise (function (resolve,reject ) { $.ajax({ url: url, success:function ( ) { resolve(response) }, error:function ( ) { reject("error" ) } }) }) } const a1 = await promisefn("http://www.xxx.com/a" ) const a2 = await promisefn("http://www.xxx.com/b" ) })()
Decorator(修饰器) core-decorators.js
@autobind
autobind装饰器使得方法中的this对象,绑定原始对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import { autobind } from 'core-decorators' ;class Person { @autobind getPerson() { return this ; } } let person = new Person();let getPerson = person.getPerson;getPerson() === person;
@readonly
readonly装饰器使得属性或方法不可写。
1 2 3 4 5 6 7 8 9 10 import { readonly } from 'core-decorators' ;class Meal { @readonly entree = 'steak' ; } var dinner = new Meal();dinner.entree = 'salmon' ;
@override
override装饰器检查子类的方法,是否正确覆盖了父类的同名方法,如果不正确会报错。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import { override } from 'core-decorators' ;class Parent { speak(first, second) {} } class Child extends Parent { @override speak() {} } class Child extends Parent { @override speaks() {} }
symbol
消除魔法字符串
魔术字符串指的是,在代码之中多次出现、与代码形成强耦合的某一个具体的字符串或者数值。风格良好的代码,应该尽量消除魔术字符串,改由含义清晰的变量代替。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 function getArea (shape, options ) { let area = 0 ; switch (shape) { case 'Triangle' : area = .5 * options.width * options.height; break ; } return area; } getArea('Triangle' , { width : 100 , height : 100 });
上面代码中,字符串Triangle就是一个魔术字符串。它多次出现,与代码形成“强耦合”,不利于将来的修改和维护。 常用的消除魔术字符串的方法,就是把它写成一个变量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 const shapeType = { triangle: 'Triangle' }; function getArea (shape, options ) { let area = 0 ; switch (shape) { case shapeType.triangle: area = .5 * options.width * options.height; break ; } return area; } getArea(shapeType.triangle, { width : 100 , height : 100 });
上面代码中,我们把Triangle写成shapeType对象的triangle属性,这样就消除了强耦合。
如果仔细分析,可以发现shapeType.triangle等于哪个值并不重要,只要确保不会跟其他shapeType属性的值冲突即可。因此,这里就很适合改用 Symbol 值。
1 2 3 const shapeType = { triangle: Symbol () };
上面代码中,除了将shapeType.triangle的值设为一个 Symbol,其他地方都不用修改。
map 把 键值对 obj 都换成 map