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 代码
相关文章:

《转》Python学习(14)-对文件的操作(一)
转自 http://www.cnblogs.com/BeginMan/p/3166644.html 一、文件对象 我理解的文件对象就是一个接口,通过这个接口对文件进行相关操作。 《Python 核心编程》上说的很晦涩,这里没有深刻理解到,希望有人能解释给我听。 >>> f open(d…

[微信小程序]组件化开发,以一个自定义模块框组件当做示例(附完整示例代码和效果图)
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 自定义组件我把它分为简单的三个步骤, 1.创建组件 --- 2.编写组件 --- 3.调用,使用组件. 第一步:创建组件 创建一个modal文件夹,里面包含 josn.wxml.wcss.js 四个文件,然后在jo…

openstack安装在虚拟机上重启之后无法启动问题
http://www.byywee.com/page/M0/S931/931767.html 运行rejoin-stack.sh脚本的核心: exec screen -c $TOP_DIR/stack-screenrc stack-screenrc文件存储启动的信息: 例如trove的启动 screen -t tr-api bash stuff "/usr/local/bin/trove-api --config…

让我们讨论一下变量,以及为什么要在JavaScript中使用它们。
by Zell Liew由Zell Liew 让我们讨论一下变量,以及为什么要在JavaScript中使用它们。 (Let’s talk about variables — and why you should use them in JavaScript.) The main purpose of coding is to solve problems. For example, what happens when you clic…

Services(服务)
开启服务有两种方式: 如果不会可以看老师的百度音乐盒的案例1、start方式:start方式的生命周期:*服务只会被开启一次,直到用户手动停止 服务才会被销毁*开启需要调用startService 会执行onCreate(),onStartCommand() *注&…

[敏捷开发实践](2) 用于开发和维持复杂产品的敏捷开发框架Scrum
[敏捷开发实践](2) 用于开发和维持复杂产品的敏捷开发框架Scrum 1,Scrum概述 上篇中提到敏捷开发有两种主流的方法,一个是XP,另一个是Scrum,本篇简要介绍Scrum方法。Scrum是一套开发和维护复杂产品的框架或…
js 实现多选框(复选框) 和单选框,下拉框功能完整示例代码附效果图
<!DOCTYPE html> <html><head><meta charset"utf-8" /><script src"http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script><title>单选框,复选框,下拉菜单简单示例</title></head…

ruby on rails_我成为了Ruby on Rails和React的贡献者,你也可以
ruby on railsI am really grateful to have contributed to a few open source projects, including two I currently use on a regular basis: Ruby on Rails and React.我非常感谢为一些开源项目做出了贡献,其中包括我目前定期使用的两个项目: Ruby o…

MySQL加密算法
1.不可逆加密: PASSWORD(),ENCRYPT(,),MD5(),SHA5()。 2.可逆的加密算法: ENCODE(,) DECODE(,):加密解密字符串。该函数有两个参数:被加密或解密的字符串和作为加密或解密基础的密…

js回调函数和函数带参数的使用示例
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 //demo1 <html><head><meta charset"UTF-8"><script src"http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script></head>&…

mvc-3模型和数据(1)
MVC和命名空间 var User function(atts) {this.attribute atts || {}; } //和具体user相关的方法 User.prototype.destroy function() {}; //和具体user不相关的函数和变量 User.fetchRemove function() {}; var user new User({name:jinks}); user.destroy();构建对象关系…

初步了解:使用JavaScript进行表达式(De Do Do Do,De Da Da Da)
by Donavon West由Donavon West 初步了解:使用JavaScript进行表达式(De Do Do Do,De Da Da Da) (A first look: do expressions in JavaScript (De Do Do Do, De Da Da Da)) This article is not about about the The Police’s 1980 hit song from alb…

div 下 的img水平居中
设置text-align:center; 这个div必须要设置宽度; 如:{text-align:center; width:100%;}转载于:https://www.cnblogs.com/zzd0916/p/6626772.html

Understanding SOAP
Understanding SOAP转载于:https://www.cnblogs.com/daishuguang/p/4227983.html

js删除组数中的某一个元素(完整代码附效果图)
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: <view class"big-logos"> <imagebindtap"addimg"src../../../image/s.png></image> <blockwx:for"{{img_arr}}"wx:key"in…

c专家编程/c陷阱_如何避免常见的初学者陷阱并像专家一样开始编码
c专家编程/c陷阱by Dmitri Grabov德米特里格拉波夫(Dmitri Grabov) 如何避免常见的初学者陷阱并像专家一样开始编码 (How to avoid common beginner pitfalls and start coding like a pro) Learning to code is tough. We’ve all encountered cryptic errors and code break…

xmpp关于后台挂起的消息接收,后台消息推送,本地发送通知
想问下,在xmpp即时通讯的项目中,我程序如果挂起了,后台有消息过来,我这边的推送不过来,所以我的通知就会收不到消息,当我重新唤醒应用的时候,他才会接收到通知,消息就会推送过来&…

[冲昏头脑]IDEA中的maven项目中学习log4j的日志操作
第一,你要有log4j的对应的包,由于我用的maven,所以直接在pom.xml文件依赖下载则可,如你尚为有此包,请自行百度下载导入,或上http://www.mvnrepository.com/搜索。上如则是我的log4j的包的版本。好了&#x…

女神推荐, 卡片,广告图 ,点击查看更多
微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文: <view><view classtitle>女神推荐 </view> <image stylemargin-top:25rpx; classtab_img src{{img list_data.q1[1].image}}></image><view classv…

aws lambda_恐怕您正在考虑AWS Lambda的冷启动完全错误
aws lambdaby Yan Cui崔燕 恐怕您正在考虑AWS Lambda的冷启动完全错误 (I’m afraid you’re thinking about AWS Lambda cold starts all wrong) When I discuss AWS Lambda cold starts with folks in the context of API Gateway, I often get responses along the line of…

python tkinter窗口弹出置顶的方法
加上下面两句即可实现root窗口的置顶显示,可以用于某些程序的消息提示,能够弹出到桌面显示 root Tk() root.wm_attributes(-topmost,1) 转载于:https://www.cnblogs.com/shuchengxiang/p/6632140.html
用Quartus II Timequest Timing Analyzer进行时序分析 :实例讲解 (一)
一,概述 用Altera的话来讲,timequest timing analyzer是一个功能强大的,ASIC-style的时序分析工具。采用工业标准--SDC(synopsys design contraints)--的约束、分析和报告方法来验证你的设计是否满足时序设计的要求。在…

软件工程与软件测试基础知识_这是我在软件工程工作九个月中学到的知识
软件工程与软件测试基础知识I’ve been working for about nine months at Dexter as a software developer. I wrote a blog post about landing the job initially, as well as a technical post about a self positioning component I made in my first couple of months at…

[bzoj1064][Noi2008]假面舞会
题意:有n个人,每个人都有一个标号,每种标号的人只能看见下一个标号的人(最后一种标号看见第一种),给定m个关系,求这个关系是否合法以及合法情况下最大和最小的方案数。$n\leqslant 10^{5},m\leqslant 10^{6…

js取一定范围内的随机整数
Math.floor(Math.random()*305 1); Math.random()*305 的作用是取0到305的随机数 加1 就是1到305的随机数, Math.floor是取整数, 所以最后的结果是0到305的随机整数 微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。

AE,按照属性值关系选择要素
if(axMapControl2.LayerCount<0) { MessageBox.Show("请加载图层后使用该功能","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Warning); } else { ILayer pLayer axMapControl2.get_Layer(0); IFeatureLayer pFeatureLayer pLayer as IFeatureLay…

aws lambda使用_如何使用AWS Lambda和S3构建无服务器URL缩短器
aws lambda使用by Daniel Ireson丹尼尔埃里森(Daniel Ireson) 如何使用AWS Lambda和S3构建无服务器URL缩短器 (How to build a Serverless URL shortener using AWS Lambda and S3) Throughout this post we’ll be building a serverless URL shortener using Amazon Web Ser…

android -volley-请求数据
private List<gson.DataBean>arrGson;//请求的数据 //请求数据的方法 public void initData() { RequestQueue mQueue Volley.newRequestQueue(getApplicationContext()); String url "http://www.fashions88.com/you/HBooks88/GetBooks88Data…

[微信小程序]动画,从顶部掉花的效果(完整代码附效果图)
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: image{ width: 100rpx;height: 100rpx;position: absolute;top: -100rpx; } 如果对您有帮助,请关注我,欢迎加入微信小程序开发交流QQ群(173683866&…

pl/sql developer连接远程数据库
本地不安装oracle client程序,直接使用pl/sql developer连接远程数据库 考虑到机子本身资源有限,一个client会占用很多资源,尝试使用不安装客户端的方式进行远程连接。 需要软件:instantclient-basic-win32-10.2.0.5.zip、pl/sql …