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 相关文章推荐
JavaScript入门教程 Cookies
Jan 31 Javascript
精通Javascript系列之Javascript基础篇
Jun 07 Javascript
JS使用ajax从xml文件动态获取数据显示的方法
Mar 24 Javascript
JS集成fckeditor及判断内容是否为空的方法
May 27 Javascript
js实现一键复制功能
Mar 16 Javascript
webpack2.0搭建前端项目的教程详解
Apr 05 Javascript
jquery实现限制textarea输入字数的方法
Sep 06 jQuery
使用javaScript实现鼠标拖拽事件
Apr 03 Javascript
AngularJS动态添加数据并删除的实例
Feb 27 Javascript
Vue中使用Sortable的示例代码
Apr 07 Javascript
微信小程序视频弹幕发送功能的实现
Dec 28 Javascript
node使用async_hooks模块进行请求追踪
Jan 28 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
PHILIPS AE3805收音机的分析打磨
2021/03/02 无线电
杏林同学录(五)
2006/10/09 PHP
PHP聊天室技术
2006/10/09 PHP
php中支持多种编码的中文字符串截取函数!
2007/03/20 PHP
Sorting Array Values in PHP(数组排序)
2011/09/15 PHP
CodeIgniter上传图片成功的全部过程分享
2013/08/12 PHP
php获取服务器端mac和客户端mac的地址支持WIN/LINUX
2014/05/15 PHP
文本框的字数限制功能jquery插件
2009/11/24 Javascript
JavaScript中valueOf函数与toString方法深入理解
2012/12/02 Javascript
jQuery插件slicebox实现3D动画图片轮播切换特效
2015/04/12 Javascript
CSS或者JS实现鼠标悬停显示另一元素
2016/01/22 Javascript
jQuery+CSS3+Html5实现弹出层效果实例代码(附源码下载)
2016/05/16 Javascript
javascript工厂模式和构造函数模式创建对象方法解析
2016/12/30 Javascript
手把手15分钟搭一个企业级脚手架
2019/09/16 Javascript
js实现固定区域内的不重叠随机圆
2019/10/24 Javascript
JS基础之逻辑结构与循环操作示例
2020/01/19 Javascript
python计算文本文件行数的方法
2015/07/06 Python
简单谈谈Python中的反转字符串问题
2016/10/24 Python
Linux下python3.7.0安装教程
2018/07/30 Python
Python异常处理操作实例详解
2018/08/28 Python
Python实现删除排序数组中重复项的两种方法示例
2019/01/31 Python
python datetime中strptime用法详解
2019/08/29 Python
python基于FTP实现文件传输相关功能代码实例
2019/09/28 Python
Python GUI库PyQt5图形和特效样式QSS介绍
2020/02/25 Python
基于Python测试程序是否有错误
2020/05/16 Python
台湾全方位线上课程与职能学习平台:TibaMe
2019/12/04 全球购物
《三顾茅庐》教学反思
2014/04/10 职场文书
新员工试用期自我鉴定
2014/04/17 职场文书
班主任个人工作反思
2014/04/28 职场文书
农业项目建议书
2014/08/25 职场文书
个人三严三实对照检查材料思想汇报
2014/09/22 职场文书
搞笑的爱情检讨书
2014/10/01 职场文书
药品开票员岗位职责
2015/04/15 职场文书
2016大学先进团支部事迹材料
2016/03/01 职场文书
无线电通信名词解释
2022/02/18 无线电
解决 redis 无法远程连接
2022/05/15 Redis