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

目录
  • 1、使用默认参数代替短路或条件
  • 2、处理多个条件
  • 3、用动态键值对替换开关(即对象文字)
  • 4、避免过多的函数参数
  • 5、使用Object.assign设置默认对象

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)

相关推荐

  • JavaScript 中断请求几种方案详解

    目录 1 Promise 中断调用链 中断Promise 包装abort方法--仿照Axios的CancelToken 2 RXJS的unsubscribe方法 3 Axios的CancelToken 1 Promise Promise有一个缺点是一旦创建无法取消,所以本质上Promise是无法被终止的. 但是我们可以通过中断调用链或中断Promise来模拟请求的中断. 中断调用链 中断调用链就是在某一个then/catch执行之后,后续的链式调用(包括then,catch,finally)不再

  • Vue.js九个性能优化技巧(值得收藏)

    目录 Functional components Child component splitting Local variables Reuse DOM with v-show KeepAlive Deferred features Time slicing Non-reactive data Virtual scrolling 总结 参考资料 这篇文章主要参考了 Vue.js 核心成员Guillaume Chau在 19 年美国的 Vue conf 分享的主题:9 Performance se

  • JavaScript实现简易购物车最全代码解析(ES6面向对象)

    本文实例为大家分享了JavaScript实现简易购物车的具体代码,供大家参考,具体内容如下 代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>ES6购物车</title> <style type="text/css"> table { width: 50%; position: relative; ma

  • JavaScript实现简易轮播图最全代码解析(ES5)

    本文实例为大家分享了JavaScript实现简易轮播图效果的具体代码,供大家参考,具体内容如下 全部代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ES5轮播图</title> <style> * {padding: 0;margin: 0;} #wrapper { position: relative; margin: 5

  • 写入cookie的JavaScript代码库 cookieLibrary.js

    /* Cookie Library -- "Night of the Living Cookie" Version (25-Jul-96) 2缔友计算机信息技术有限公司,涂聚文 geovindu@163.com 互相交流 3 Written by: Bill Dortch, hIdaho Design <geovindu@163.com> 4 The following functions are released to the public domain. 5http:/

  • java FastJson的简单用法

    目录 1.前言 1.1.FastJson的介绍: 1.2.FastJson的特点: 1.3.FastJson的简单说明: 2.FastJson的用法 2.1.JSON格式字符串与JSON对象之间的转换 2.2.JSON格式字符串与javaBean之间的转换 2.3.javaBean与json对象间的之间的转换 总结 参考 1.前言 1.1.FastJson的介绍: JSON(javaScript Object Notation)是一种轻量级的数据交换格式.主要采用键值对({"name"

  • JavaScript实现简易放大镜最全代码解析(ES5)

    本文实例为大家分享了JavaScript实现简易放大镜的具体代码,供大家参考,具体内容如下 完整代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ES5放大镜</title> <style> .box { width: 170px; height: 180px; margin: 100px 200px; border: 1px

  • angularJS实现表格部分列展开缩起示例代码

    AngularJS 简介 AngularJS 是一个 JavaScript 框架.它可通过 <script> 标签添加到 HTML 页面. AngularJS 通过 指令 扩展了 HTML,且通过 表达式 绑定数据到 HTML. AngularJS 是一个 JavaScript 框架 AngularJS 是一个 JavaScript 框架.它是一个以 JavaScript 编写的库. AngularJS 是以一个 JavaScript 文件形式发布的,可通过 script 标签添加到网页中:

  • JavaScript实现简易轮播图最全代码解析(ES6面向对象)

    本文实例为大家分享了JavaScript实现简易轮播图的具体代码,供大家参考,具体内容如下 完整代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ES6轮播图</title> <script></script> <style> * { margin: 0; padding: 0; } .box { wi

  • 从基础开始建立一个JS代码库第1/2页

    由于后台程序会过滤掉单引号,所以有些地方如果出现莫民奇妙的空格,就表示单引号,特此说明. /** * @author Super Sha * QQ:770104121 * Email:supersha@foxmail.com * All Rights Reserved! */ (function(){ //原创 function $(s){ if (!s) return false; return s.constructor == String ? document.getElementById

随机推荐