如何实现JavaScript代码整洁?

整洁的JavaScript代码对于代码的可维护性和减少错误至关重要。遵循命名规范,限制函数参数数量,理解引用类型的可变性,确保函数单一职责,避免扩展原型,利用多态替换条件语句,以及使用getter和setter,都是实现代码整洁的有效方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

整洁的代码不仅仅是让人看起来舒服,更重要的是遵循一些规范能够让你的代码更容易维护,同时降低bug几率。

小编创建了一个群,有前端系统的学习资料和帮助解答问题,欢迎各位小白和大牛们的加入,点击:加群

  1. 用命名的变量代替数组下标
// bad
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(
  // 下标1,2不易于理解
  address.match(cityZipCodeRegex)[1],
  address.match(cityZipCodeRegex)[2]
);
// good
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
// 使用数组解构更好的命名变量
const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
  1. 函数的参数最好 <= 2个,尽量避免3个。
    如果有很多参数就利用 object 传递,并使用解构。

注意 object array 这些引用类型的值是 mutable 的。

  1. 一个函数只做一件事。
    好处在于 compose, test, and reason about 。

  2. 不要自行扩展原型
    如果想扩展原型,可以先继承再添加方法,防止污染。

// bad
Array.prototype.diff = function diff(comparisonArray) {
  const hash = new Set(comparisonArray);
  return this.filter(elem => !hash.has(elem));
};
// good
class SuperArray extends Array {
  diff(comparisonArray) {
    const hash = new Set(comparisonArray);
    return this.filter(elem => !hash.has(elem));
  }
}
  1. 用多态来代替条件语句
// bad
if (type === 'text') {
    // do something
} else if (type === 'select') {
    // do something else
}

我个人写这种代码的一种常用方式是:

const control = {
    text: {
        mapper() {},
        restore(){},
        name: 'this is a text field',
    },
    select: {
        mapper() {},
        restore(){},
        name: 'this is a select field',
    }
}

control[type].mapper();

实际上就是多态(polymorphism),也可以考虑用 class 的方式,大概这样:

class Field {
    ...
}

class TextField extends Field {
    mapper(){}
    restore(){}
    name = 'this is a text field';
}

class SelectField extends Field {
    mapper(){}
    restore(){}
    name = 'this is a select field';
}
  1. 使用 getter 和 setter 函数。
// bad
function makeBankAccount() {
  // ...

  return {
    balance: 0
    // ...
  };
}

const account = makeBankAccount();
account.balance = 100;
// good
function makeBankAccount() {
  // this one is private
  let balance = 0;

  // a "getter", made public via the returned object below
  function getBalance() {
    return balance;
  }

  // a "setter", made public via the returned object below
  function setBalance(amount) {
    // ... validate before updating the balance
    balance = amount;
  }

  return {
    // ...
    getBalance,
    setBalance
  };
}

const account = makeBankAccount();
account.setBalance(100);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值