In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the bad JS code styles?" the content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the bad JS code styles".
1. Variable correlation
(1) definition of the number of variables
NO: abuse variable
Let kpi = 4; / / We have never used function example () {var a = 1; var b = 2; var c = aquib; var d = Cobb 1; var e = Dancia; return e;}
YES: data can be used only once or not, so it doesn't need to be loaded into variables.
Delete let kpi = 4; / / delete it if it is useless, otherwise you won't dare to delete it after three months. I wonder if you will use function example () {var a = 1; var b = 2; return 2a delete 1;}
(2) naming of variables
NO: an abbreviation for feeling good about yourself.
Let fName = 'jackie'; / / looks like the naming is quite standard, abbreviations, hump method are used, ESlint various testing tools are passed, what is But,fName? At this point, do you want to say what What are you is doing? Let lName = 'willen'; / / this question is the same as above
YES: you don't need to comment on every variable. You can read it by name.
Let firstName = 'jackie'; / / is it clear at a glance? Less than once was sprayed let lastName = 'willen'; ```
(3) specific variables
NO: unspecified parameter
If (value.length
< 8) { // 为什么要小于8,8表示啥?长度,还是位移,还是高度?Oh,my God!! .... } YES:添加变量 const MAX_INPUT_LENGTH = 8; if (value.length < MAX_INPUT_LENGTH) { // 一目了然,不能超过***输入长度 .... } (4)变量的命名 NO:命名过于啰嗦 let nameString; let theUsers; YES: 做到简洁明了 let name; let users; (5)使用说明性的变量(即有意义的变量名) NO:长代码不知道啥意思 const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\]+[,\s]+(.+?)s*(d{5})?$/; saveCityZipCode( address.match(cityZipCodeRegex)[1], // 这个公式到底要干嘛,对不起,原作者已经离职了。自己看代码 address.match(cityZipCodeRegex)[2], // 这个公式到底要干嘛,对不起,原作者已经离职了。自己看代码 ); YES:用变量名来解释长代码的含义 const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\]+[,\s]+(.+?)s*(d{5})?$/; const [, city, zipCode] = address.match(cityZipCodeRegex) || []; saveCityZipCode(city, zipCode); (6)避免使用太多的全局变量 NO:在不同的文件不停的定义全局变量 name.js window.name = 'a'; hello.js window.name = 'b'; time.js window.name = 'c'; //三个文件的先后加载顺序不同,都会使得window.name的值不同,同时,你对window.name的修改了都有可能不生效,因为你不知道你修改过之后别人是不是又在别的说明文件中对其的值重置了。所以随着文件的增多,会导致一团乱麻。 YES:少用或使用替代方案 你可以选择只用局部变量。通过(){}的方法。 如果你确实用很多的全局变量需要共享,你可以使用vuex,redux或者你自己参考flux模式写一个也行。 (7)变量的赋值。 NO:对于求值获取的变量,没有兜底。 const MIN_NAME_LENGTH = 8; let lastName = fullName[1]; if(lastName.length >MIN_NAME_LENGTH) {/ / so you have successfully buried a hole in your code, have you ever considered if fullName = ['jackie']? In this way, the program explodes as soon as it runs. Why don't you try. .... }
YES: for evaluating variables, do a good job.
Const MIN_NAME_LENGTH = 8; let lastName = fullName [1] | |'; / / complete the backing. If you can't get it in fullName [1], you won't have to assign a undefined, or at least an empty character. Basically, both the variable type of lastName and the features on the String,String prototype chain can be used without error. It won't become a undefined. If (lastName.length > MIN_NAME_LENGTH) {.... } in fact, there are many evaluation variables in the project, and you need to make a good background for each evaluation variable. Let propertyValue = Object.attr | | 0; / / because the Object.attr may be empty, so it needs to be covered. However, the assignment variable does not need to be backdated. Let a = 2; / / because you have a bottom, so don't hold it in your pocket. Let myName = 'Tiny'; / / because you have a bottom, so don't hold it in your pocket.
Second, function correlation
(1) function naming
NO: cannot know the return value type from naming
Function showFriendsList () {....} / / now ask, do you know whether this returns an array, an object, or true or false. Can you answer it? If you can answer, I'll treat you to the full table of Song he Lou, and please don't take it seriously.
Yes: for functions that return true or false, * starts with should/is/can/has
Function shouldShowFriendsList () {...} function isEmpty () {...} function canCreateDocuments () {...} function hasLicense () {...}
(2) the function * * is a pure function.
NO: don't let the output of the function be fickle.
Function plusAbc {/ / the output of this function will be changeable, because once the value returned by api is changed, the value of the same input function, but the result returned by the function may not be the same. Var c = fetch ('.. / api'); return astatbreadc;}
YES: the function function uses pure function, the input is consistent, and the output is always unique.
Function plusAbc {/ / the value of the same input function, but the result returned by the function is always the same. Return axibac;}
(3) function parameter transfer
NO: there is no description for passing parameters
What do page.getSVG (api, true, false) / / true and false mean? it's not clear at a glance.
YES: there are instructions for passing parameters.
Page.getSVG ({imageApi: api, includePageBackground: true, / / know at a glance what these true and false mean compress: false,})
(4) the action function should begin with a verb
NO: unable to distinguish function intent
Function emlU (user) {.... }
YES: the intention of the function is obvious at the beginning of the verb.
Function sendEmailToUser (user) {.... }
(5) one function performs an independent function. Do not mix multiple functions with one function.
This is the most important rule in software engineering, and when functions need to do more, they will be more difficult to write, test, understand, and combine. When you can extract a function to complete only one action, they will be able to ReFactor easily and your code will be easier to read. If you strictly follow this rule, you will be ahead of many developers.
NO: functions are confusing. A function contains multiple functions. * like an old master who can beat a hundred by a hundred, he is beaten to death by random punches (complex functions).
Function sendEmailToClients (clients) {clients.forEach (client = > {const clientRecord = database.lookup (client) if (clientRecord.isActive ()) {email (client)}})}
YES: function disassembly
Function sendEmailToActiveClients (clients) {/ / it is easy to maintain and reuse clients.filter (isActiveClient) .forEach (email)} function isActiveClient (client) {const clientRecord = database.lookup (client) return clientRecord.isActive ()}
(6) give priority to imperative programming
NO: programming with for loops
For (I = 1; I + + item) / / is not easy to understand, just add one of the values of a to b. Now almost all for loops in javascript can be replaced by imperative programming such as map,filter,find,some,any,forEach.
(7) excessive use of if else in the function.
No: too much if else
If (a = 1) {...} else if (a = 2) {...} else if (a = 3) {...} else {...}
YES: can be replaced with switch or array
Switch (a) {case 1:.... Case 2:.... Case 3:.... Default:.... } Or let handler = {1: () = > {....}, 2: () = > {....}. 3: () = > {....}, default: () = > {....}} handler [a] () | | handler ['default'] ()
Third, try to use ES6, if possible, the new grammar in ES7
(list only the most commonly used new grammars. To be honest, some new grammars are not commonly used.)
(1) use the arrow function as much as possible
NO: using traditional functions
Function foo () {/ / code} YES: use the arrow function let foo = () = > {/ / code}
(2) connection string
NO: use the traditional + sign
Var message = 'Hello' + name +', it's'+ time + 'now'
YES: using template characters
Var message = `Hello ${name}, it's ${time} now`
(3) using deconstruction assignment
NO: use traditional assignments:
Var data = {name: 'dys', age: 1}; var name = data.name; var age = data.age; var fullName = [' jackie', 'willen']; var firstName = fullName [0]; var lastName = fullName [1]
YES: use structure assignment:
Const data = {name:'dys', age:1}; const {name, age} = data; / / is it simple and clear that var fullName = ['jackie',' willen']; const [firstName, lastName] = fullName
(4) use class class as much as possible.
NO: using traditional function prototype chain to realize inheritance
Typical ES5 classes (function) are less readable in terms of inheritance, construction, and method definition, and class is preferred when inheritance is needed. If there is too much code, it will be omitted.
YES: using ES6 class to implement inheritance
Class Animal {constructor (age) {this.age = age} move () {/ *... * /}} class Mammal extends Animal {constructor (age, furColor) {super (age) this.furColor = furColor} liveBirth () {/ *... * /}} class Human extends Mammal {constructor (age, furColor, languageSpoken) {super (age) FurColor) this.languageSpoken = languageSpoken} speak () {/ *... * /}} Thank you for your reading The above is the content of "what are the bad JS code styles?" after the study of this article, I believe you have a deeper understanding of what the bad JS code style is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.