John Au-Yeung
来源:medium
译者:前端小智
有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。javascript
本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及个人系列文章。前端
JavaScript 是一种易于学习的编程语言,编写运行并执行某些操做的程序很容易。然而,要编写一段干净的JavaScript 代码是很困难的。java
在本文中,咱们将介绍一些与清理 JavaScript 函数和类有关的重构思想。git
在使用参数以前,咱们应该删除对参数的赋值,并将参数值赋给变量。github
例如,咱们可能会写这样的代码:面试
const discount = (subtotal) => { if (subtotal > 50) { subtotal *= 0.8; } }
对比上面的代码,咱们能够这样写:算法
const discount = (subtotal) => { let _subtotal = subtotal; if (_subtotal > 50) { _subtotal *= 0.8; } }
由于参数有多是经过值或者引用传递的,若是是引用传递的,直接负值操做,有些结果会让感到困惑。编程
本例是经过值传递的,但为了清晰起见,咱们仍是将参数赋值给变量了。数组
咱们能够将一个方法变成本身的函数,以便全部类均可以访问它。微信
例如,咱们可能会写这样的代码:
const hello = () => { console.log('hello'); } class Foo { hello() { console.log('hello'); } //... } class Bar { hello() { console.log('hello'); } //... }
咱们能够将hello
方法提取到函数中,以下所示:
const hello = () => { console.log('hello'); } class Foo { //... } class Bar { //... }
因为hello
方法不依赖于this
,而且在两个类中都重复,所以咱们应将其移至其本身的函数中以免重复。
相对流程式的写法,咱们想用一个更清晰的算法来代替,例如,咱们可能会写这样的代码:
const doubleAll = (arr) => { const results = [] for (const a of arr) { results.push(a * 2); } return results; }
对比上面的代码,咱们能够这样写:
const doubleAll = (arr) => { return arr.map(a => a * 2); }
经过数组方法替换循环,这样doubleAll
函数就会更加简洁。
若是有一种更简单的方法来解决咱们的需求,那么咱们就应该使用它。
在两个类之间,咱们能够把其中一个类的方法移动到另外一个类中,例如,咱们可能会写这样的代码:
class Foo { method() {} } class Bar { }
假如,咱们在 Bar
类使用 method
的次数更多,那么应该把 method
方法移动到 Bar
类中, Foo
若是须要在直接调用 Bar
类的中方法便可。
class Foo { } class Bar { method() {} }
除了移动方法外,咱们还能够移动字段。例如,咱们可能会写这样的代码:
class Foo { constructor(foo) { this.foo = foo; } } class Bar { }
跟移动方法的缘由相似,咱们有时这么改代码:
class Foo { } class Bar { constructor(foo) { this.foo = foo; } }
咱们能够将字段移至最须要的地方
若是咱们的类很复杂而且有多个方法,那么咱们能够将额外的方法移到新类中。
例如,咱们可能会写这样的代码:
class Person { constructor(name, phoneNumber) { this.name = name; this.phoneNumber = phoneNumber; } addAreaCode(areaCode) { return `${areaCode}-${this.phoneNumber}` } }
咱们能够这样重构:
class PhoneNumber { constructor(phoneNumber) { this.phoneNumber = phoneNumber; } addAreaCode(areaCode) { return `${areaCode}-${this.phoneNumber}` } } class Person { constructor(name, phoneNumber) { this.name = name; this.phoneNumber = new PhoneNumber(phoneNumber); } }
上面咱们将Person
类不太相关的方法addAreaCode
移动了本身该处理的类中。
经过这样作,两个类只作一件事,而不是让一个类作多件事。
咱们能够从复杂的类中提取代码,这些复杂的类能够将多种功能添加到本身的类中。
此外,咱们能够将方法和字段移动到最经常使用的地方。
将值分配给参数值会形成混淆,所以咱们应该在使用它们以前将其分配给变量。
代码部署后可能存在的BUG无法实时知道,过后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给你们推荐一个好用的BUG监控工具 Fundebug。
原文:https://levelup.gitconnected....
有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。
本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及个人系列文章。