javascript 代码_如何使您JavaScript代码保持简单并提高其可读性

javascript 代码

by Leonardo Lima

莱昂纳多·利马(Leonardo Lima)

如何使您JavaScript代码保持简单并提高其可读性 (How to keep your JavaScript code simple and increase its readability)

After a few years working almost exclusively with Ruby on Rails and some jQuery, I changed my focus to front-end development. I discovered the beauties of JavaScript ES6 syntax and the exciting modern libraries such as React and Vue. I started to implement new features using nothing but ES6 Vanilla JavaScript, and fell instantly in love with all this new class abstraction and those arrow functions.

几年后,我几乎完全与Ruby on Rails和某些jQuery一起工作,之后我将工作重点转向了前端开发。 我发现了JavaScript ES6语法的美丽之处以及令人兴奋的现代库,例如React和Vue。 我开始只使用ES6 Vanilla JavaScript来实现新功能,并且立即爱上了所有这些新类抽象和那些箭头功能。

Nowadays, I’m generating large amounts of JavaScript code. But, since I consider myself a JavaScript Padawan, there’s yet a lot of room for improvement. Through my studies and observations, I’ve learned that even with the use of syntactic sugars featured in ES6, if you don’t follow the main principles of SOLID, your code has a high chance of becoming complex to read and maintain.

如今,我正在生成大量JavaScript代码。 但是,由于我认为自己是JavaScript Padawan,因此还有很多改进的空间。 通过我的研究和观察,我了解到,即使使用ES6中的语法糖,如果您不遵循SOLID的主要原理,您的代码也很有可能变得复杂,难以阅读和维护。

To demonstrate what I’m talking about, I’ll walk you through one fantastic Code Review session I had last week with a buddy of mine. We are going to start with a 35-lines JavaScript Class and will finish with a beautiful 11-lines code piece using only slick functions. With patience and resilience, you will be able to observe and apply the pattern to your own codebase.

为了演示我在说什么,我将带您完成上周与我的一个伙伴进行的精彩的代码审查会议。 我们将从一个35行JavaScript类开始,并以仅使用平滑函数的一个优美的11行代码段结束。 有了耐心和韧性,您将能够观察到该模式并将其应用于自己的代码库。

功能 (The feature)

What I needed to do was quite simple and trivial: get some information from the page and send a request to a third-party tracking service. We were building an event tracker on the client side and tracking some page actions along with it.

我需要做的非常简单且琐碎:从页面中获取一些信息,然后将请求发送给第三方跟踪服务。 我们正在客户端构建一个事件跟踪器,并跟踪一些页面操作。

The code examples below implement the same task using different code design tactics.

下面的代码示例使用不同的代码设计策略来实现相同的任务。

第1天-使用ES6类语法(又称为对象原型模式包装器) (Day 1 — Using ES6 Class syntax (aka Object Prototype Pattern wrapper))

You can notice above that I started smart: isolating the generic tracker SuccessPlanTracker to be reused in another page besides the Empty Index.

您可以在上面看到我开始聪明了:隔离通用跟踪器SuccessPlanTracker以便在Empty Index之外的另一页中重用。

But, wait a minute. If this is an empty index tracker, what on earth is this foreigner TrackNewPlanAdd doing there?

但是,请稍等。 如果这是一个空的索引跟踪器,那么这个外国人TrackNewPlanAdd在做什么?

第2天-摆脱Class样板代码 (Day 2 — Getting rid of Class boilerplate code)

Okay, now the file name clearly reflects the feature responsibility and, look at that, there is no more EmptyIndexTracker class giving us less boilerplate code. Learn more here and here. We are using simple functions variables and, man, what a good catch using those shining ES6 Object Spread dots.

好的,现在文件名清楚地反映了功能职责,并且,没有更多的EmptyIndexTracker类,给我们提供了更少的样板代码。 在此处此处了解更多信息 。 我们正在使用简单的函数变量,伙计们,使用那些闪亮的ES6对象扩展点是一个不错的选择。

I find out that the querySelectorAll method already returns a List, so we are able to remove the Array.from() function from Array.from(document.getElementsByClassName('js-empty-index-tracking')) `. Remember that getElementsByClassName method returns an object.

我发现querySelectorAll方法已经返回一个列表,因此我们能够从Array.from(document.getElementsByClassName('js-empty-index-tracking')) `.删除Array.from()函数Array.from(document.getElementsByClassName('js-empty-index-tracking')) `. 请记住, getElementsByClassName方法返回一个对象。

Also, since the central responsibility is to bind HTML elements, the document.addEventListener('DOMContentLoaded') function invocation doesn’t belongs to the file anymore.

另外,由于主要职责是绑定HTML元素,所以document.addEventListener('DOMContentLoaded')函数调用不再属于该文件。

Good job!

做得好!

第3天-消除ES5的旧做法并进一步隔离职责。 (Day 3 — Removing ES5 old practices and isolating responsibilities even more.)

If you pay close attention, there is no SuccessPlanTracker class in the code above — it suffered the same fate as the old EmptyIndexTracker. The class-killing mindset, once installed, spreads and multiplies itself. But don’t fear, my good lad.

如果您密切注意,上面的代码中没有SuccessPlanTracker类-它与旧的EmptyIndexTracker命运相同。 一旦安装了杀人观念,它就会自我传播和繁殖。 但是,别担心,我的好孩子。

Remember, always try to keep your JavaScript files simple. There is no need to know about the states of class instances, and the classes were exposing practically only one method.

请记住,请始终尝试使您JavaScript文件保持简单。 无需了解类实例的状态,并且这些类实际上仅公开一种方法。

Don’t you think using the ES6 class abstraction was a little bit of overkill?

您不认为使用ES6类抽象有点过大吗?

Did you also notice that I removed the variables instances from the top of the file? This practice remounts to ES5, and we don’t need to worry so much about it now that we have ES6+ syntax.

您是否还注意到我从文件顶部删除了变量实例? 这种做法将重新安装到ES5,现在有了ES6 +语法,我们就不必为此担心了。

Finally, the last major change in this third version. Our empty index tracker binder now does only one thing: elements binding.

最后,这是第三个版本中的最后一个主要更改。 现在,我们空的索引跟踪程序装订器只做一件事:元素绑定。

Following those steps brought the code very close to the Single Responsibility Principle — one of the most important SOLID principles.

遵循这些步骤,使代码非常接近单一职责原则,这是最重要的SOLID原则之一。

第4天-避免DOM随意操作 (Day 4 — Avoiding DOM sloppy manipulation)

Hey, there are more lines now, you liar!

嘿,骗子,现在还有更多台词!

The thing is that our third version was a little broken. We were inappropriately mutating DOM Elements datasets in the line properties.emptyIndexAction = button.dataset.trackingIdentifier;.

关键是我们的第三个版本有点破。 我们在行properties.emptyIndexAction = button.dataset.trackingIdentifier;中对DOM Elements数据集进行了不适当的变异properties.emptyIndexAction = button.dataset.trackingIdentifier;

The property of one button was being passed to another button, generating messed up tracking events. To solve this situation, we removed the responsibility of assigning the emptyIndexAction property from the binding loop to a proper function by creating its own scoped method trackAction().

一个按钮的属性被传递给另一个按钮,从而产生混乱的跟踪事件。 为了解决这种情况,我们通过创建其自己的作用域方法trackAction()来消除了将绑定emptyIndexAction属性分配给适当的函数的trackAction()

By adding those extra lines, we improved our code, better encapsulating each action.

通过添加这些额外的行,我们改进了代码,更好地封装了每个动作。

最后,总结并写下来 (Finally, to wrap up and write down)
  • If you want to design and write marvelous pieces of code, you need to be willing to explore further and go beyond the limits of a proper and modern syntax.

    如果您要设计和编写出色的代码,则需要愿意进一步探索并超越适当和现代语法的限制。
  • Even if the first version of your code ended up being simple and readable, it doesn’t necessarily mean that the system has a good design or that it follows at least one of the SOLID principles.

    即使您的代码的第一版最终变得简单易读,也不一定意味着系统具有良好的设计或至少遵循SOLID原则之一。

  • It’s essential to accept constructive code reviews and let other developers point out what you can do better.

    必须接受建设性的代码审查,并让其他开发人员指出您可以做得更好的事情。
  • To keep your code simple, you need to think bigger.

    为了使您的代码简单,您需要考虑更大。

Thank you very much for reading the article. Have another refactoring example or code review lesson to share? Please drop a comment below! Also, you can help me share this message with others by clapping and sharing it.

非常感谢您阅读本文。 还有其他重构示例或代码复习课可以分享吗? 请在下面发表评论! 另外,您可以通过拍手和分享来帮助我与他人分享此信息。

ProTip to-go: Here’s a very useful ES6 (ES2015+) cheatsheet

普罗蒂普到-GO:这是一个非常有用的ES6(ES2015 +) 的cheatsheet

*Cheers to @anderson06 for being such a good code ‘pal giving me awesome feedbacks.

*感谢@ anderson06,因为它是一个很好的代码pal,给了我很棒的反馈。

翻译自: https://www.freecodecamp.org/news/how-to-keep-your-javascript-code-simple-and-increase-its-readability-94d6a949afc4/

javascript 代码

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值