js基石之—易读、易复用、易重构的 JavaScript 代码规范
易读、易复用、易重构的 JavaScript 代码规范
1.变量命名规范有意义
Bad: const yyyymmdstr = moment().format("YYYY/MM/DD"); Good: const currentDate = moment().format("YYYY/MM/DD");
2. 给变量定义名字
Bad: // What the heck is 86400000 for? setTimeout(blastOff, 86400000); Good: // Declare them as capitalized named constants. const MILLISECONDS_IN_A_DAY = 86_400_000; setTimeout(blastOff, MILLISECONDS_IN_A_DAY);
3.函数的变量定义初始值
Bad: function createMicrobrewery(name) { const breweryName = name || "Hipster Brew Co."; // ... } Good: function createMicrobrewery(name = "Hipster Brew Co.") { // ... }
4.函数的形参过多时候,用对象代替多个参数
Bad: function createMenu(title, body, buttonText, cancellable) { // ... } createMenu("Foo", "Bar", "Baz", true); Good: function createMenu({ title, body, buttonText, cancellable }) { // ... } createMenu({ title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true });
5.函数应该只做一件事情
Bad: function emailClients(clients) { clients.forEach(client => { const clientRecord = database.lookup(client); if (clientRecord.isActive()) { email(client); } }); } Good: function emailActiveClients(clients) { clients.filter(isActiveClient).forEach(email); } function isActiveClient(client) { const clientRecord = database.lookup(client); return clientRecord.isActive(); }
6.函数名应该告诉这个函数是用来干嘛的
Bad: function addToDate(date, month) { // ... } const date = new Date(); // It's hard to tell from the function name what is added addToDate(date, 1); Good: function addMonthToDate(month, date) { // ... } const date = new Date(); addMonthToDate(1, date)
7.定义对象使用深拷贝
Good: const menuConfig = { title: "Order", // User did not include 'body' key buttonText: "Send", cancellable: true }; function createMenu(config) { config = Object.assign( { title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true }, config ); // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} // ... } createMenu(menuConfig);
参考地址来源 ://github.com/ryanmcdermott/clean-code-javascript