javascript 编码_7种javascript编码标准以提高可读性

javascript 编码

重点 (Top highlight)

Coding standards can help with the below:

编码标准可以帮助以下方面:

  • Keeps the code consistent

    保持代码一致
  • Easier to read and understand

    易于阅读和理解
  • Easier to maintainer

    易于维护
  • Easier to refactor

    易于重构

The coding standards below are my own opinion on what can help with the above points, using what I have experienced whilst developing and reviewing other developers JavaScript.

下面的编码标准是我自己的观点 ,即在开发和审查其他开发人员JavaScript时,我会使用自己的经验来解决上述问题。

对promise使用异步等待 (Use async-await over promises)

Pick one to use where you can. If you prefer promises that is fine also, just try to be consistent as this will help readability.

选择一个可以使用的地方。 如果您更希望使用Promise,也请尝试保持一致,因为这将有助于提高可读性。

I pick async-await because I find it easier to read than promises. I asked my team and every developer in my team said async-await was easier to read as well!

我选择async-await是因为我发现它比promise容易阅读。 我问我的团队,团队中的每个开发人员都说async-await也更容易阅读!

This becomes more evident when you have to make more than one call as well e.g. one API needs data from another API.

当您必须进行多个调用时(例如,一个API需要来自另一个API的数据),这一点变得更加明显。

Fail:

失败:

const getData = url => {
fetch(url)
.then((response) => {
// return Json from first call
return response.json()
})
.then((data) => {
// do stuff with data, call second fetch
return fetch(url + "/" + data.someID)
})
.then((response) => {
// return Json from first call
return response.json();
})
.then((data) => {
// do stuff with `data` from second fetch
})
.catch((error) => {
console.log('Requestfailed', error)
})
.finally(() => {
// runs everytime
});
}

Pass:

通过:

const getData = async url => {
try {
// fetch first call and get data
let data = await fetch(url).json();// fetch second call and get data
data = await fetch(url + "/" + data.someID).json();// do stuff with `data` from second fetch}
catch(err) {
console.log('Error: ', err)
}
finally {
// runs everytime
}
}

变数 (Variables)

#使用 const let 超过 var (# Use const & let over var)

Fail:

失败:

var myVar = 10;
var iNeverHaveToChange = "me";

Pass:

通过:

let myVar = 10;
const iNeverHaveToChange = "me";

Using const helps readability as developers know it can’t be reassigned!

使用const有助于提高可读性,因为开发人员知道无法重新分配它!

Using let over var is more because var can cause issues with scope. It's probably too much to get into for this post as it probably deserves a post by its self.

使用let over var会更多,因为var可能会导致范围问题。 该帖子可能涉及太多内容,因为它可能值得自己发表。

#避免使用全局变量 (# Avoid using global variables)

Minimize the use of global variables. Global variables are a terribly bad idea. The problem with global variables and functions is that they can be overwritten by other scripts.

尽量减少使用全局变量。 全局变量是一个非常糟糕的主意。 全局变量和函数的问题在于它们可以被其他脚本覆盖。

#命名变量 (# Naming variables)

Try and come up with names that make sense are not too long. Naming things in coding is actually one of the hardest things to do!

尝试并提出有意义的名称不要太长。 在编码中命名事物实际上是最难的事情之一!

let should be camelCase

let驼峰

const if at the top of a file use upper case snake case. MY_CONST . If not at the top of the file use camelCase

const如果在文件顶部)使用大写的蛇形大写。 MY_CONST 。 如果不在文件顶部,请使用camelCase

API调用 (API Calls)

#选择一种方法并坚持下去 (#Pick a method and stick with it)

By method I mean one of the below.

通过方法,我的意思是以下之一。

  • XMLHttpRequest

    XMLHttpRequest
  • fetch

  • Axios

    Axios
  • jQuery

    jQuery的

Nowadays Axios & Fetch are the preferred way to go. One main benefit of using Axios instead of fetch its wide browser support. Even old browsers like IE11 can run Axios without any issue. Although there are fetchpolyfills so depends on what is more important for you.

如今,Axios&Fetch是首选的方式。 使用Axios而不是fetch其广泛的浏览器支持的主要好处之一。 即使是像IE11这样的旧版浏览器,也可以毫无问题地运行Axios。 尽管可以fetch polyfill,但要取决于对您来说更重要的内容。

#使通话可重用 (#Make the calls reusable)

Instead of just having the calls everywhere in your application. Have modules for your calls. This makes it more consistent and way easier to refactor. Also if something changes on the API you should only have to change it once!

不仅仅是在应用程序中到处都有调用。 有呼叫模块。 这使得它更加一致并且更易于重构。 另外,如果API发生更改,则只需更改一次!

进口货 (Imports)

#尽可能使用命名导入而不是默认导入 (# Use named imports over default imports where possible)

This makes everything consistent and you know what to expect. Also, editors don’t provide autocomplete suggestions.

这使所有内容保持一致,您知道会发生什么。 另外,编辑者不提供自动完成建议。

The issue with defaultimports is that any developer can name it whatever they want. This can make refactoring tricky!

default导入的问题在于,任何开发人员都可以随心所欲地为其命名。 这会使重构变得棘手!

Fail:

失败:

export default class Apple {// This should be apple :/
import banana from "apple.js"

Pass:

通过:

export class Apple {import { Apple } from "apple.js"

#尝试按字母顺序订购进口商品。 (# Try and order your imports alphabetically.)

A sorted list of import declarations make it easier for developers to read and find necessary imports later

导入声明的排序列表使开发人员在以后阅读和查找必要的导入时更容易

Fail:

失败:

import 
import Apple from "apple.js";
import { g, e } from "other.js";
import { lion, bear, dog, cat } from "animals";

Pass:

通过:

import { bear, cat, dog, lion } from "animals";
import { e, g } from "other.js";
import Apple from "apple.js";
import banana from "banana.js";

Eslint can really help with this, below are the default rules. This can come down to style and what is best for you. I recommend picking one and sticking to it.

Eslint确实可以提供帮助,以下是默认规则。 这可以归结为风格,什么才是最适合您的。 我建议选择一个并坚持下去。

{
"sort-imports": ["error", {
"ignoreCase": false,
"ignoreDeclarationSort": false,
"ignoreMemberSort": false,
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"],
"allowSeparatedGroups": false
}]
}

Dom操作 (Dom Manipulation)

Depending on if you’re using a framework you may not need to worry about the below points to much as the framework should deal with dom-manipulation for you

取决于您是否使用框架,您可能不必担心以下几点,因为框架应该为您处理dom操作

#查询选择 (# Query selecting)

Use querySelector and querySelectorAll over getElementById and getElementsByTagName methods.

querySelector querySelectorAll 过度 getElementById getElementsByTagName 方法。

There is almost no difference between querySelectorand getElementsByTagNamemethods. querySelectoris newer and allows for more complex selections.

querySelectorgetElementsByTagName方法之间几乎没有区别。 querySelector较新,并且允许进行更复杂的选择。

For consistency, it is probably best to choose one and stick with it throughout your scripts. Using a mix just ends up looking messy!

为了保持一致性,最好在整个脚本中选择一个并坚持使用。 使用混合最终看起来很凌乱!

Fail:

失败:

let element = document.let elements = document.

Pass:

通过:

// Selects element which has the ID "#unique_id"
let element = document.querySelector("#unique_id");// Selects the first element which has the class "element_class"
let element = document.querySelector(".element_class");// Select all the element which have the class "element_class"
let element = document.querySelectorAll(".element_class");

#在添加样式时使用CSS类 (# Use CSS classes over adding styles)

This makes the code a lot easier to read and more reusable as you can see from below.

从下面可以看到,这使代码更易于阅读和可重用。

Fail:

失败:

const customerName = document.querySelector('#customerName');
const form = document.querySelector('form');form.onsubmit = (e) => {
e.preventDefault();
}input.oninvalid = () => {
customerName.style.borderColor = 'red';
customerName.style.borderStyle = 'solid';
customerName.style.borderWidth = '1px';
}

Pass:

通过:

// JavaScript
const customerName = document.querySelector('#customerName');
const form = document.querySelector('form');form.onsubmit = (e) => {
e.preventDefault();
}input.oninvalid = () => {
customerName.className = 'invalid';
}// CSS
.invalid {
border: 1px solid red;
}

功能 (Functions)

#尽可能使用ES6箭头功能 (# Use ES6 arrow functions where possible)

Arrow functions are a more concise syntax for a writing function expression. They’re are anonymous and change the way this binds in functions.

箭头函数是编写函数表达式的更简洁的语法。 它们是匿名的,并会更改this函数绑定的方式。

Fail(s):

失败:

var multiply = function(a, b) {
return a* b;
};

Pass:

通过:

const multiply = (a, b) => { return a * b};

#命名功能 (# Naming functions)

functions should be camelCase . myFunction

functions应该是camelCasemyFunction

Fail(s):

失败:

const Multiply = (a, b) => { return a * b};
const MULTIPLY = (a, b) => { return a * b};

Pass:

通过:

const multiply = (a, b) => { return a * b};

结论 (Conclusion)

Coding standards in any language can really help with the readability of an application and the maintainability. A lot of them come down to preference and to reiterate the above are my own opinion. The main point is to be consistent as they really help scale up an application in a clean way.

任何语言的编码标准都可以真正帮助提高应用程序的可读性和可维护性。 我很多人都选择偏爱并重申以上几点 。 要点是要保持一致,因为它们确实有助于以一种干净的方式扩展应用程序。

One big thing which I think is missing from the above list is how to structure the application. I didn’t add this because this can be dependent on your application and if you’re using a framework.

我认为上述列表中缺少的一件事是如何构建应用程序。 我没有添加它,因为这可能取决于您的应用程序以及您是否正在使用框架。

One other thing that can be hard if you’re working in a team is enforcing coding standards. Here are some ideas to help:

如果您在团队中工作,那么可能很难做的另一件事就是强制执行编码标准。 这里有一些建议可以帮助您:

  • Desk reviews, going through the code line by line.

    案头审查,逐行通过代码。
  • Linting or some kind of code analyser

    整理或某种代码分析器
  • Creating a consistent application, where every developer knows what they need to create /update.

    创建一个一致的应用程序,每个开发人员都知道创建/更新所需的内容。

Below are some more simple coding standards which can help write clean JavaScript code!

以下是一些更简单的编码标准,可以帮助编写干净JavaScript代码!

Hope you’ve enjoyed reading!

希望您喜欢阅读!

普通英语JavaScript (JavaScript In Plain English)

Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

喜欢这篇文章吗? 如果是这样,请订阅我们的YouTube频道解码,以获得更多类似的内容

翻译自: https://medium.com/javascript-in-plain-english/7-javascript-coding-standards-for-readability-consistency-9a3d81821397

javascript 编码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值