this.queue = [...contents];
}
Queue.prototype.pop = function () {
const value = https://www.isolves.com/it/cxkf/yy/js/2019-10-16/this.queue[0];
this.queue.splice(0, 1);
return value;
};
// good
class Queue {
constructor(contents = []) {
this.queue = [...contents];
}
pop() {
const value = https://www.isolves.com/it/cxkf/yy/js/2019-10-16/this.queue[0];
this.queue.splice(0, 1);
return value;
}
}
14. 用`extends`实现继承
// bad
const inherits = require('inherits');
function PeekableQueue(contents) {
Queue.apply(this, contents);
}
inherits(PeekableQueue, Queue);
PeekableQueue.prototype.peek = function () {
return this._queue[0];
}
// good
class PeekableQueue extends Queue {
peek() {
return this._queue[0];
}
}
15.可以返回`this`来实现方法链
// bad
Jedi.prototype.jump = function () {
this.jumping = true;
return true;
};
Jedi.prototype.setHeight = function (height) {
this.height = height;
};
const luke = new Jedi();
luke.jump(); // => true
luke.setHeight(20); // => undefined
// good
class Jedi {
jump() {
this.jumping = true;
return this;
}
setHeight(height) {
this.height = height;
return this;
}
}
const luke = new Jedi();
luke.jump()
.setHeight(20);
16.如果没有具体说明,类有默认的构造方法 。一个空的构造函数或只是代表父类的构造函数是不需要写的 。
// bad
class Jedi {
constructor() {}
getName() {
return this.name;
}
}
// bad
class Rey extends Jedi {
// 这种构造函数是不需要写的
constructor(...args) {
super(...args);
}
}
// good
class Rey extends Jedi {
constructor(...args) {
super(...args);
this.name = 'Rey';
}
}
17. 一个路径只 import 一次 。
// bad
import foo from 'foo';
// … some other imports … //
import { named1, named2 } from 'foo';
// good
import foo, { named1, named2 } from 'foo';
// good
import foo, {
named1,
named2,
} from 'foo';
18. 做幂运算时用幂操作符 `**`。
// bad
const binary = Math.pow(2, 10);
// good
const binary = 2 ** 10;
19.三元表达式不应该嵌套,通常是单行表达式 。
// bad
const foo = maybe1 > maybe2
? "bar"
: value1 > value2 ? "baz" : null;
// better
const maybeNull = value1 > value2 ? 'baz' : null;
const foo = maybe1 > maybe2
? 'bar'
: maybeNull;
// best
const maybeNull = value1 > value2 ? 'baz' : null;
const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
20.避免不需要的三元表达式
// bad
const foo = a ? a : b;
const bar = c ? true : false;
const baz = c ? false : true;
// good
const foo = a || b;
const bar = !!c;
const baz = !c;
21. 如果 `if` 语句中总是需要用 `return` 返回,那后续的 `else` 就不需要写了 。`if` 块中包含 `return`,它后面的 `else if` 块中也包含了 `return`,这个时候就可以把 `return` 分到多个 `if` 语句块中 。
// bad
function foo() {
if (x) {
return x;
} else {
return y;
}
}
// bad
function cats() {
if (x) {
return x;
} else if (y) {
return y;
}
}
// bad
function dogs() {
if (x) {
return x;
} else {
if (y) {
return y;
}
}
}
// good
function foo() {
if (x) {
return x;
}
return y;
}
// good
function cats() {
if (x) {
return x;
}
if (y) {
return y;
}
}
// good
function dogs(x) {
if (x) {
if (z) {
return y;
}
} else {
return z;
}
}
推荐阅读
- 老茶是时光流逝中的静默
- 茶中的自由
- 夜晚中的茶香
- 爱情中的茶香
- 苹果|苹果iOS 15.5首个公测版发布:小幅更新、开发全新内置应用
- 茶是场邂逅 爱上茶杯中的小幸福
- 分享几个前端技术文档网站
- 岁月中的茶
- WEB 前端模块化都有什么?
- Android 开发:ActionBar & 消息 & 通知 & 广播全在这篇
