5种方法告诉你如何使JavaScript 代码库更干净


Posted in Javascript onSeptember 15, 2021

1、使用默认参数代替短路或条件

默认参数通常比短路更干净。

function SomeMethod(paramThatCanBeUndefined) {

const localValue = paramThatCanBeUndefined || "Default Value";
   console.log(localValue)
   // ...
}
SomeMethod() // Default Value
SomeMethod("SomeValue") // SomeValue

尝试以下方法:

function SomeMethod(
  console.log(paramThatCanBeUndefined)
  // ...
}
SomeMethod() // Default Value
SomeMethod("SomeValue") // SomeValue

声明:Falsy值,如'',"",false,null,0,和NaN将不会被默认值替代:

function SomeMethod(paramThatCanBeUndefined = "Default Value") {        
  console.log(paramThatCanBeUndefined)  
  // ...
}
SomeMethod(null) // will not Default Value, will null Instead
SomeMethod("SomeValue") // SomeValue

2、处理多个条件

const conditions = ["Condition 2","Condition String2"];
someFunction(str){
  if(str.includes("someValue1") || str.includes("someValue2")){
    return true
  }else{
    return false
  }
}

一种更干净的方法是:

someFunction(str){
   const conditions = ["someValue1","someValue2"];
   return conditions.some(condition=>str.includes(condition));
}

3、用动态键值对替换开关(即对象文字)

开关版本(或将开关替换为if / else):

const UserRole = {
  ADMIN: "Admin",
  GENERAL_USER: "GeneralUser",
  SUPER_ADMIN: "SuperAdmin",
};
function getRoute(userRole = "default role"){


  switch(userRole){
    case UserRole.ADMIN:
      return "/admin"
    case UserRole.GENERAL_USER:
        return "/GENERAL_USER"
    case UserRole.SUPER_ADMIN:
        return "/superadmin"
    default:
      return "/" 
  }

}
console.log(getRoute(UserRole.ADMIN)) // return "/admin"
console.log(getRoute("Anything")) // return Default path
console.log(getRoute()) // return Default path
console.log(getRoute(null)) // return Default path

// More cases if new arrive
// You can think if else instead of switch

动态键值对版本:

const UserRole = {
   ADMIN: "Admin",
   GENERAL_USER: "GeneralUser",
   SUPER_ADMIN: "SuperAdmin",
};
function getRoute(userRole = "default role"){
 const appRoute = {
  [UserRole.ADMIN]: "/admin",
  [UserRole.GENERAL_USER]: "/user",
  [UserRole.SUPER_ADMIN]: "/superadmin"
 };
 return appRoute[userRole] || "Default path";
}
console.log(getRoute(UserRole.ADMIN)) // return "/admin"
console.log(getRoute("Anything")) // return Default path
console.log(getRoute()) // return Default path
console.log(getRoute(null)) // return Default path
// No more switch/if-else here.
// Easy to Further expansion

4、避免过多的函数参数

function myFunction(employeeName,jobTitle,yrExp,majorExp){
 return `${employeeName} is working as ${jobTitle} with ${yrExp}    years of experience in ${majorExp}`
}
//output be like John is working as Project Manager with 12 year of experience in Project Management
// you can call it via
console.log(myFunction("John","Project Manager",12,"Project Management"))
//    ***** PROBLEMS ARE *****
// Violation of 'clean code' principle
// Parameter sequencing is important
// Unused Params warning if not used
// Testing need to consider a lot of edge cases.

这是一种更清洁的方法:

function myFunction({employeeName,jobTitle,yrExp,majorExp}){
 return `${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp}`
}
//output be like John is working as Project Manager with 12 year of experience in Project Management
// you can call it via
const mockTechPeople = {
  employeeName:"John",
  jobTitle:"Project Manager",
  yrExp:12,
  majorExp:"Project Management"
}
console.log(myFunction(mockTechPeople))
// ES2015/ES6 destructuring syntax is in action
// map your desired value to variable you need.

5、使用Object.assign设置默认对象

这看起来很繁琐:

const someObject = {
 title: null,
 subTitle: "Subtitle",
 buttonColor: null,
 disabled: true
};
function createOption(someObject) {
 someObject.title = someObject.title || "Default Title";
 someObject.subTitle = someObject.subTitle || "Default Subtitle";
 someObject.buttonColor = someObject.buttonColor || "blue";
 someObject.disabled = someObject.disabled !== undefined ?  someObject.disabled : true;
 return someObject
}
console.log(createOption(someObject));

// Output be like 
// {title: 'Default Title', subTitle: 'Subtitle', buttonColor: 'blue', disabled: true}

这种方法看起来更好:

const someObject = {
  title: null,
  subTitle: "Subtitle",
  buttonColor: null,
  disabled: true
 };
 function creteOption(someObject) {
  const newObject = Object.assign({
   title: "Default Title",
   subTitle: "Default Subtitle",
   buttonColor: "blue",
   disabled: true
 },someObject)
 return newObject
 }
 console.log(creteOption(someObject));

到此这篇关于如何使JavaScript 代码库更干净 5种方法告诉你的文章就介绍到这了,更多相关使 JavaScript 代码库更干净的5种方法内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!谢谢大家的阅读

Javascript 相关文章推荐
xml 封装与解析(javascript和C#中)
Jul 26 Javascript
DOM基础教程之使用DOM控制表格
Jan 20 Javascript
js判断当前页面在移动设备还是在PC端中打开
Jan 06 Javascript
JavaScript实战之菜单特效
Aug 16 Javascript
canvas知识总结
Jan 25 Javascript
bootstrap手风琴折叠示例代码分享
May 22 Javascript
JavaScript 用fetch 实现异步下载文件功能
Jul 21 Javascript
深入理解JavaScript的async/await
Aug 05 Javascript
iview在vue-cli3如何按需加载的方法
Oct 31 Javascript
解决layer.msg 不居中 ifram中的问题
Sep 05 Javascript
用JS实现选项卡
Mar 23 Javascript
基于javascript canvas实现五子棋游戏
Jul 08 Javascript
JavaScript小技巧带你提升你的代码技能
Sep 15 #Javascript
javascript函数式编程基础
Sep 15 #Javascript
15个值得收藏的JavaScript函数
Sep 15 #Javascript
详解JavaScript中Arguments对象用途
详细谈谈JavaScript中循环之间的差异
Aug 23 #Javascript
javascript代码简写的几种常用方式汇总
Aug 23 #Javascript
vue使用Google Recaptcha验证的实现示例
You might like
PHP使用array_fill定义多维数组的方法
2015/03/18 PHP
php命令行写shell实例详解
2018/07/19 PHP
Javascript实例教程(19) 使用HoTMetal(6)
2006/12/23 Javascript
jquery 锁定弹出层实现代码
2010/02/23 Javascript
JavaScript ( (__ = !$ + $)[+$] + ({} + $)[_/_] +({} + $)[_/_] )
2011/02/25 Javascript
jQuery实现密保互斥问题解决方案
2013/08/16 Javascript
JS创建自定义表格具体实现
2014/02/11 Javascript
js和jquery中循环的退出和继续学习记录
2014/09/06 Javascript
使用mouse事件实现简单的鼠标经过特效
2015/01/30 Javascript
jQuery匹配文档链接并添加class的方法
2015/06/26 Javascript
AngularJS实现全选反选功能
2015/12/08 Javascript
点评js异步加载的4种方式
2015/12/22 Javascript
详解JavaScript中的事件流和事件处理程序
2016/05/20 Javascript
Bootstarp基本模版学习教程
2017/02/01 Javascript
JS实现双击内容变为可编辑状态
2017/03/03 Javascript
webpack-dev-server远程访问配置方法
2018/02/22 Javascript
vue实现商品列表的添加删除实例讲解
2020/05/14 Javascript
js实现盒子拖拽动画效果
2020/08/09 Javascript
Python如何快速实现分布式任务
2017/07/06 Python
聊聊Python中的pypy
2018/01/12 Python
Python递归实现打印多重列表代码
2020/02/27 Python
python numpy实现多次循环读取文件 等间隔过滤数据示例
2020/03/14 Python
Django使用Profile扩展User模块方式
2020/05/14 Python
Python如何使用ElementTree解析xml
2020/10/12 Python
matplotlib制作雷达图报错ValueError的实现
2021/01/05 Python
英国第二大营养品供应商:Vitabiotics
2016/10/01 全球购物
英国文具、办公用品和科技商店:Ryman
2018/09/27 全球购物
应届生如何写自荐信
2014/01/05 职场文书
项目管理计划书
2014/01/09 职场文书
更夫岗位责任制
2014/02/11 职场文书
国际会计专业求职信
2014/08/04 职场文书
毕业生银行实习自我鉴定
2014/10/14 职场文书
贫困生助学金感谢信
2015/01/21 职场文书
生日宴会家属答谢词
2015/09/29 职场文书
JavaScript异步操作中串行和并行
2021/11/20 Javascript
手把手带你彻底卸载MySQL数据库
2022/06/14 MySQL