关于javascript:JavaScript重构技巧-函数和类

2次阅读

共计 2302 个字符,预计需要花费 6 分钟才能阅读完成。

John Au-Yeung
起源:medium
译者:前端小智

有幻想,有干货,微信搜寻 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试残缺考点、材料以及我的系列文章。

JavaScript 是一种易于学习的编程语言,编写运行并执行某些操作的程序很容易。然而,要编写一段洁净的 JavaScript 代码是很艰难的。

在本文中,咱们将介绍一些与清理 JavaScript 函数和类无关的重构思维。

不要间接对参数赋值

在应用参数之前,咱们应该删除对参数的赋值,并将参数值赋给变量。

例如,咱们可能会写这样的代码:

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 已收录,有一线大厂面试残缺考点、材料以及我的系列文章。

正文完
 0