好的代码实践
我们有一个方法:buildAnimal(),它需要三个参数:accessory, animal, color。
function buildAnimal(accessory, animal, color){...}1
然后我们需要加一个参数,我们需要怎么做?很简单啊,直接在方法名后面加不就好了吗。
但是我们是好的程序员,怎么能这么没追求啊是不是:
“Functions should have a small number of arguments. No argument is best, followed by one, two, and three. More than three is very questionable and should be avoided with prejudice.”Robert C. Martin’s Clean Code
我们开始重构,把所有的参数放到一个对象里面:animalData,它有下面三个属性:animal, color, hairType
function buildAnimal(animalData){...}1
如果要加参数,直接加到animalData的属性里面就好了。但是,又有一个问题了。如果我们要冲对象里面拿数据:可能要这样:
function buildAnimal(animalData){ let accessory = animalData.accessory, animal = animalData.animal, color = animalData.color, hairType = animalData.hairType; ...}1234567
代码重复了很多,很不优雅对不对!
解构
先定义一个对象:
let obj = { accessory: 'horn', animal: 'horse', color: 'purple', hairType:'curly'}123456
解构的原理是:从一个对象一次性解析出多个属性给不同变量,比如数组中解析出元素,从map/set中解析出数据等。
模式
任何结构都有两个部分1 解构源: 等号右边是要解构的对象。2 解构目标:等号左边是要解构的对象。