• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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种方法内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界!谢谢大家的阅读


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
React实现二级联动(左右联动)发布时间:2022-02-05
下一篇:
React实现二级联动的方法发布时间:2022-02-05
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap