登录
首页 >  文章 >  前端

通用编码标准 JavaScript

来源:dev.to

时间:2024-08-06 18:36:27 262浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《通用编码标准 JavaScript》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

通用编码标准 JavaScript

通用编码标准

  1. 有意义的名字:
    • 使用有意义且具有描述性的变量和函数名称。
    • 除了循环计数器之外,避免使用缩写和单字母名称。
   // good
   const userage = 25;
   function calculatetotalprice(items) { ... }

   // bad
   const a = 25;
   function calc(items) { ... }
  1. 一致的命名约定:
    • 变量和函数使用驼峰命名法。
    • 使用 pascalcase 命名类名。
   const userage = 25;
   function calculatetotalprice(items) { ... }
   class userprofile { ... }
  1. 避免重复:
    • 遵循 dry(don’t repeat yourself)原则,将重复的代码封装到函数中。
   // good
   function calculatediscount(price, discount) { ... }
   const price1 = calculatediscount(100, 10);
   const price2 = calculatediscount(200, 20);

   // bad
   const price1 = 100 - 10;
   const price2 = 200 - 20;
  1. 错误处理:
    • 将 api 调用和其他异步操作包装在 try-catch 块中。
   async function fetchdata() {
     try {
       const response = await fetch('api/url');
       const data = await response.json();
       return data;
     } catch (error) {
       console.error('error fetching data:', error);
     }
   }
  1. 边缘情况:
    • 始终考虑边缘情况并验证输入。
   function getuserage(user) {
     if (!user || !user.age) {
       return 'age not available';
     }
     return user.age;
   }
  1. 一致的格式:
    • 遵循一致的代码格式风格(缩进、间距等)。使用 prettier 等工具来自动化此操作。
   if (condition) {
     dosomething();
   } else {
     dosomethingelse();
   }

代码组织

  1. 模块化:
    • 将代码分解为小的、可重用的模块或函数。
   // utils.js
   export function calculatediscount(price, discount) { ... }

   // main.js
   import { calculatediscount } from './utils.js';
  1. 关注点分离:
    • 将不同的关注点(例如,ui 逻辑、业务逻辑、数据处理)分离到不同的文件或函数中。
   // ui.js
   function updateui(data) { ... }

   // data.js
   async function fetchdata() { ... }

   // main.js
   import { updateui } from './ui.js';
   import { fetchdata } from './data.js';

最佳实践

  1. 使用严格模式:
    • 始终启用严格模式来捕获常见的编码错误。
   'use strict';
  1. 使用常量:
    • 对不改变的值使用常量。
   const max_users = 100;
  1. 避免全局变量:
    • 尽量减少全局变量的使用,以避免冲突和意外行为。
   // good
   (function() {
     const localvariable = 'this is local';
   })();

   // bad
   var globalvariable = 'this is global';
  1. 评论和文档:
    • 编写注释和文档来解释代码的目的和功能。
   /**
    * calculates the total price after applying a discount.
    * @param {number} price - the original price.
    * @param {number} discount - the discount to apply.
    * @returns {number} - the total price after discount.
    */
   function calculatetotalprice(price, discount) { ... }
  1. 使用 promises 和异步/等待进行错误处理:
    • 更喜欢使用 promise 和 async/await 进行异步操作,并将它们包装在 try-catch 块中以进行错误处理。
   // good
   async function fetchdata() {
     try {
       const response = await fetch('api/url');
       const data = await response.json();
       return data;
     } catch (error) {
       console.error('error fetching data:', error);
     }
   }

   // bad
   function fetchdata(callback) {
     fetch('api/url')
       .then(response => response.json())
       .then(data => callback(data))
       .catch(error => console.error('error fetching data:', error));
   }
  1. 对象解构:
    • 使用对象解构以简洁的方式从对象中提取多个属性。
   // Good
   const vehicle = { make: 'Toyota', model: 'Camry' };
   const { make, model } = vehicle;

   // Bad
   const vehicleMake = vehicle.make;
   const vehicleModel = vehicle.model;

通过遵循这些标准,您可以确保您的 javascript 代码干净、可维护且高效。

今天关于《通用编码标准 JavaScript》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>