浏览 1104
扫码
格式化
格式化是主观的。 就像其它规则一样, 没有必须让你遵守的硬性规则。 重点是不要因为格式去争论, 这
里有大量的工具来自动格式化, 使用其中的一个即可! 因
为做为工程师去争论格式化就是在浪费时间和金钱。
针对自动格式化工具不能涵盖的问题(缩进、 制表符还是空格、 双引号还是单引号等), 这里有一些指南。
使用一致的大小写
JavaScript 是无类型的, 所以大小写告诉你关于你的变量、 函数等的很多事情。 这些规则是主观的,
所以你的团队可以选择他们想要的。 重点是, 不管你们选择了什么, 要保持一致。
不好的:
const DAYS_IN_WEEK = 7;const daysInMonth = 30;const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];const Artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];function eraseDatabase() {}function restore_database() {}class animal {}class Alpaca {}
好的:
const DAYS_IN_WEEK = 7;const DAYS_IN_MONTH = 30;const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];const artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];function eraseDatabase() {}function restoreDatabase() {}class Animal {}class Alpaca {}
函数的调用方与被调用方应该靠近
如果一个函数调用另一个, 则在代码中这两个函数的竖直位置应该靠近。 理想情况下,保持被调用函数在被
调用函数的正上方。 我们倾向于从上到下阅读代码, 就像读一章报纸。 由于这个原因, 保持你的代码可
以按照这种方式阅读。
不好的:
class PerformanceReview {constructor(employee) {this.employee = employee;}lookupPeers() {return db.lookup(this.employee, 'peers');}lookupManager() {return db.lookup(this.employee, 'manager');}getPeerReviews() {const peers = this.lookupPeers();// ...}perfReview() {this.getPeerReviews();this.getManagerReview();this.getSelfReview();}getManagerReview() {const manager = this.lookupManager();}getSelfReview() {// ...}}const review = new PerformanceReview(user);review.perfReview();
好的:
class PerformanceReview {constructor(employee) {this.employee = employee;}perfReview() {this.getPeerReviews();this.getManagerReview();this.getSelfReview();}getPeerReviews() {const peers = this.lookupPeers();// ...}lookupPeers() {return db.lookup(this.employee, 'peers');}getManagerReview() {const manager = this.lookupManager();}lookupManager() {return db.lookup(this.employee, 'manager');}getSelfReview() {// ...}}const review = new PerformanceReview(employee);review.perfReview();