Front-end development specifications: JavaScript specifications

JavaScript style guide

variable

variable declaration
  • Standard variables use small camel case, such as userInfo, activeIndex
  • Constants should be in all uppercase letters and connected with underscores, such as BASE_URL, DOMAIN
  • Constructor, capitalize the first letter
  • Variable names need to be semantic. Do not declare names such as a, bb, div1, xcx, etc.
  • Temporary variables with small scope can be abbreviated, such as: str, num, obj, un, arr.
  • It is forbidden to use let, always use let or const
Declare data to avoid data with unclear intent
//正例:
const MINUTES_IN_A_YEAR = 525600;
for (let i = 0; i < MINUTES_IN_A_YEAR; i++) {
    
    
  runCronJob();
}

//反例:
// 525600 是什么?
for (let i = 0; i < 525600; i++) {
    
    
  runCronJob();
}
Avoid duplicate descriptions
//正例:
let Car = {
    
    
  make: "Honda",
  model: "Accord",
  color: "Blue",
};

//反例:
let Car = {
    
    
  carMake: "Honda",
  carModel: "Accord",
  carColor: "Blue",
};

function

Function parameters (ideally no more than 2)

Limiting the number of function arguments is necessary to make testing functions easier. Too many parameters will make it difficult to use effective test cases to test each parameter of the function.

Functions with more than three parameters should be avoided. Usually, more than two parameters means that the function is too complex, and you need to re-optimize your function. When multiple parameters are indeed needed, in most cases you can consider encapsulating these parameters into an object.

It is very convenient to define objects in JS. When multiple parameters are required, an object can be used instead.

//正例:
let menuConfig = {
    
    
  title: 'Foo',
  body: 'Bar',
  buttonText: 'Baz',
  cancellable: true
}

function createMenu(menuConfig) {
    
    
  ...
}

//反例:
function createMenu(title, body, buttonText, cancellable) {
    
    
  ...
}
Function naming
  • Camel case naming, uniform use of verbs, or verb + noun form
//正例:
jumpPage、openUserInfoDialog

//反例:
go、nextPage、show、open、login
  • Request data method, ending with data
// good
getListData   postFormData

// bad
getList  postForm
  • Try to start with common words
setget、open、close、jump

Attached: Verbs used in function methods

get 获取/set 设置,
add 增加/remove 删除
create 创建/destory 移除
start 启动/stop 停止
open 打开/close 关闭,
read 读取/write 写入
load 载入/save 保存,
create 创建/destroy 销毁
begin 开始/end 结束,
backup 备份/restore 恢复
import 导入/export 导出,
split 分割/merge 合并
inject 注入/extract 提取,
attach 附着/detach 脱离
bind 绑定/separate 分离,
view 查看/browse 浏览
edit 编辑/modify 修改,
select 选取/mark 标记
copy 复制/paste 粘贴,
undo 撤销/redo 重做
insert 插入/delete 移除,
add 加入/append 添加
clean 清理/clear 清除,
index 索引/sort 排序
find 查找/search 搜索,
increase 增加/decrease 减少
play 播放/pause 暂停,
launch 启动/run 运行
compile 编译/execute 执行,
debug 调试/trace 跟踪
observe 观察/listen 监听,
build 构建/publish 发布
input 输入/output 输出,
encode 编码/decode 解码
encrypt 加密/decrypt 解密,
compress 压缩/decompress 解压缩
pack 打包/unpack 解包,
parse 解析/emit 生成
connect 连接/disconnect 断开,
send 发送/receive 接收
download 下载/upload 上传,
refresh 刷新/synchronize 同步
update 更新/revert 复原,
lock 锁定/unlock 解锁
check out 签出/check in 签入,
submit 提交/commit 交付
push 推/pull 拉,
expand 展开/collapse 折叠
begin 起始/end 结束,
start 开始/finish 完成
enter 进入/exit 退出,
abort 放弃/quit 离开
obsolete 废弃/depreciate 废旧,
collect 收集/aggregate 聚集
Use default parameters to simplify code
//正例:
function writeForumComment(subject = 'No subject', body = 'No text') {
    
    
  ...
}

//反例:
function writeForumComment(subject, body) {
    
    
  subject = subject || 'No Subject';
  body = body || 'No text';
}
Use Object.assign to set the default object
//正例:
let menuConfig = {
    
    
  title: "Order",
  // User did not include 'body' key
  buttonText: "Send",
  cancellable: true,
};

function createMenu(config) {
    
    
  config = Object.assign(
    {
    
    
      title: "Foo",
      body: "Bar",
      buttonText: "Baz",
      cancellable: true,
    },
    config,
  );

  // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
  // ...
}

createMenu(menuConfig);

//反例:
let menuConfig = {
    
    
  title: null,
  body: "Bar",
  buttonText: null,
  cancellable: true,
};

function createMenu(config) {
    
    
  config.title = config.title || "Foo";
  config.body = config.body || "Bar";
  config.buttonText = config.buttonText || "Baz";
  config.cancellable = config.cancellable === undefined ? config.cancellable : true;
}

createMenu(menuConfig);

concurrent

Async/Await is a better choice than Promises

Promises are a better choice than callbacks, but async and await in ES7 beat Promises.

When ES7 features can be used, you can try to use them instead of Promises.

//正例:
async function getCleanCodeArticle() {
    
    
  try {
    
    
    let request = await require("request-promise");
    let response = await request.get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin");
    let fileHandle = await require("fs-promise");

    await fileHandle.writeFile("article.html", response);
    console.log("File written");
  } catch (err) {
    
    
    console.log(err);
  }
}

//反例:
require("request-promise")
  .get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
  .then(function (response) {
    
    
    return require("fs-promise").writeFile("article.html", response);
  })
  .then(function () {
    
    
    console.log("File written");
  })
  .catch(function (err) {
    
    
    console.error(err);
  });

Error priority handling

Errors that will cause problems will be dealt with first

//正例:
function getCleanCodeArticle() {
    
    
  let request = await require("request-promise");
  let res = await request.get("https://en.wikipedia.org/wikRobert_Cecil_Martin");
  if(res.code===403){
    
    
    return '暂无权限'
  }
  else if(res.code!==200){
    
    
    return '请求异常'
  }
  return '请求成功'
}

//反例:
function getCleanCodeArticle() {
    
    
  let request = await require("request-promise");
  let res = await request.get("https://en.wikipedia.org/wikRobert_Cecil_Martin");
  if(res.code===200){
    
    
    return '请求成功'
  }
  else if(res.code===403){
    
    
    return '暂无权限'
  }
  return '请求异常'
}

Comment

Only comment code with a certain complexity of business logic

Comments are not necessary. Good code can be understood at a glance without too many unnecessary comments.

//正例:
function hashIt(data) {
    
    
  let hash = 0;
  let length = data.length;

  for (let i = 0; i < length; i++) {
    
    
    let char = data.charCodeAt(i);
    hash = (hash << 5) - hash + char;

    // Convert to 32-bit integer
    hash = hash & hash;
  }
}

//反例:
function hashIt(data) {
    
    
  // The hash
  let hash = 0;

  // Length of string
  let length = data.length;

  // Loop through every character in data
  for (let i = 0; i < length; i++) {
    
    
    // Get character code.
    let char = data.charCodeAt(i);
    // Make the hash
    hash = (hash << 5) - hash + char;
    // Convert to 32-bit integer
    hash = hash & hash;
  }
}
Functions can be code commented using jsDoc

jsDoc

/**
 * 返回一本书.
 * @param {string} title - 书本的标题.
 * @param {string} author - 书本的说明
 */
function Book(title, author) {
    
    }

brackets

The following keywords must be followed by braces (even if the code block contains only one line): if, else, for, while, do, switch, try, catch, finally, with.

jshint

  • Use '=', '!'Replace'==', '!=';
  • Do not add methods to the prototypes of built-in objects, such as Array and Date;
  • Do not declare a variable in the code of the inner scope and then access the variable with the same name in the outer scope;
  • Do not add parentheses in unnecessary places, for example: delete(ab);
  • Don’t declare variables but not use them;
  • Don’t make assignments where comparisons should be made;
  • The debugger should not appear in the submitted code;
  • Do not declare functions inside loops;

Miscellaneous

  • The reference to context this can only be named using one of '_this', 'that', 'self';
  • The falling through and no default situations of switch must be specially explained in comments;

Guess you like

Origin blog.csdn.net/Big_YiFeng/article/details/127357097