昨晚在阅读大佬源码时看到了这样一段
login(values: any): Observable<any> {
return this.httpClient.post(`${SERVER_URL}/login`, values, {responseType: 'text'})
.pipe(tap(jwt => this.handleJwtResponse(jwt)));
}
今天在闲看别人技术文章时发现原来这是ES6中的 动态字符串,还是蛮幸运的解决了这个疑惑(#^.^#)
动态字符串
不要使用“双引号”,一律用单引号或反引号
// low
const a = "foobar";
const b = 'foo' + a + 'bar';
// best
const a = 'foobar';
const b = `foo${a}bar`;
同时将其他一些收获的东西也贴出来(^▽^)
拷贝数组
// 还在用for i 你就太low了
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// cool ! 使用扩展运算符(...)拷贝数组
const itemsCopy = [...items];
引入模块
使用import取代require,因为Module是Javascript模块的标准写法。
// bad
const moduleA = require('moduleA');
const func1 = moduleA.func1;
const func2 = moduleA.func2;
// good
import { func1, func2 } from 'moduleA';
输出模块
使用export输出变量,拒绝module.exports
import React from 'react';
class Breadcrumbs extends React.Component {
render() {
return <nav />;
}
};
export default Breadcrumbs;
- 输出单个值,使用export default
- 输出多个值,使用export
- export default与普通的export不要同时使用
编码规范
模块输出一个函数,首字母应该小写
function getData() {
}
export default getData;
模块输出一个对象,首字母应该大写
const Person = {
someCode: {
}
};
export default Person ;
更加简洁直观的class写法
// low
function Queue(contents = []) {
this._queue = [...contents];
}
Queue.prototype.pop = function() {
const value = this._queue[0];
this._queue.splice(0, 1);
return value;
}
// good
class Queue {
constructor(contents = []) {
this._queue = [...contents];
}
pop() {
const value = this._queue[0];
this._queue.splice(0, 1);
return value;
}
}
一次性初始化完全
不要声明之后又给对象添加新属性
// low
const a = {};
a.x = 3;
// good
const a = { x: null };
a.x = 3;
如果一定非要加请使用Object.assign
const a = {};
Object.assign(a, { x: 3 });
如果对象的属性名是动态的,可以在创造对象的时候,使用属性表达式定义
// low
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};
再简洁一点
在定义对象时,能简洁表达尽量简洁表达
var ref = 'some value';
// low
const atom = {
ref: ref,
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// good
const atom = {
ref,
value: 1,
addValue(value) {
return atom.value + value;
},
};