In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I would like to talk to you about the seven excellent practices of JavaScript, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
1. When you write a constructor, add a method on .prototype
According to my first two years of experience with JavaScript, if you are a novice to JavaScript, you may be a bit unfamiliar with this part.
(remember, this doesn't apply to classes, because classes already attach methods to their prototype.)
The following is an example of a constructor:
FunctionFrog (name, gender) {this.name= name this.gender= gender} Frog.prototype.leap=function (feet) {console.log (`Leaping ${feet} ft into the Air`)}
Why not attach the leap method directly, as in the following example?
FunctionFrog (name, gender) {this.name= name this.gender= gender this.leap=function (feet) {console.log (`Leaping ${feet} ft into the air`)}}
When methods are added directly to prototype, they are shared among all instances created by the constructor.
In other words, using the previous example, if you create three separate Frog (from this.leap = function () {...}), and then end up creating three separate copies. This is a problem because the leap method always stays the same and there is no need to make your own copy on the instance.
It eventually leads to performance degradation that could have been avoided. The this.name and this.gender attributes need to be defined on the instance, because in real life, frog may have its own name and gender, so they are created at the instance level.
Here is an example of this approach used by the popular request package (on GitHub).
two。 Use TypeScript
TypeScript not only provides strong defenses against type safety, but also helps prevent errors, and has been widely used in the JavaScript community.
Using TypeScript enables the compiler to monitor potential errors and display warnings before the code runs.
But this is far from explaining why TypeScript can be applied to any situation. The best thing about TypeScript is that it allows new features in JavaScript to be used before mainstream browsers support them, because they are compiled into earlier versions of JavaScript and therefore run in older browsers.
3. Write tests
If you want to take a project seriously, you must use testing so that the application is more predictable, error-free, and flexible to future changes. In other words, if you plan to do a project that will stand the test of time, there is no better way than to set up tests throughout your code. The more tests you put into your code, the more confidence you will have in it when you apply it to a production environment.
What is the best part of the test? Is the ability to catch errors and prevent them from appearing-is there anyone who doesn't want that ability? I'm sure I want it. That's why I wrote unit tests in the project.
4. When using JSON.parse or JSON.stringify, be sure to consider using try/catch
In JavaScript, when you pass JSON as input to JSON.parse, you need a properly formatted JSON as the first parameter. If the format is incorrect, the JSON parsing error will be prompted.
The danger from JSON parsing errors is that accepting invalid JSON can cause the application to crash. One of our web projects recently failed because another built-in package did not install JSON.parse in try/catch. The web page eventually becomes invalid, and because the JavaScript runtime is corrupted, the error cannot be fixed unless the built-in package fixes it.
SyntaxError: Unexpected token} in JSON at position 107
Valid JSON input should not always be expected, because it will receive strange characters such as ">", which is common today.
5. Use the regular .type attribute to distinguish
This method is great and has been widely used. React developers may see this every day, especially when working with Redux.
Using a similar approach can also make the development process extremely simple, because it can even record itself well.
FunctioncreateSpecies (type, name, gender) {if (type = 'frog') {returncreateFrog (name, gender)} elseif (type =' human') {returncreateHuman (name, gender)} elseif (type = undefined) {thrownewError ('Cannot create a species with an unknown type')}} const myNewFrog = createSpecies (' frog', 'sally',' female')
6. Use the factory function (factory function)
If you don't know what a factory function is, it is a function that returns an object (it is neither a class nor a constructor). With this simple concept, you can take advantage of JavaScript and its features to create powerful and robust applications.
It is important to know that when a function is called by the new keyword, it is no longer a factory function.
Why use the factory function?
Using the factory function, you can easily generate an object instance without involving classes or new keywords.
In essence, they mean that they will eventually be treated as functions, that is, they can be used to combine objects, functions, and even Promise functions. This means that factory functions can be mixed and matched to create an upgraded version of the factory function, and then continue to be combined with other functions or objects to create stronger factory functions. The possibilities are endless.
With this in mind, it begins to shine when combined with good code practice.
The following is a simple example of a factory function:
FunctioncreateFrog (name) {const children = [] return {addChild (frog) {children.push (frog)},}} const mikeTheFrog = createFrog ('mike')
When you use enough factory functions, you realize that factory functions are more reusable than class constructors. This reduces the amount of code, shortens the code refactoring time (because the factory function will eventually return any object), and shortens the management time from one code to another.
7. Make the function as simple as possible
As we all know, there are probably large functions in JavaScript that do many things at the same time.
Novice programmers may think this is a good thing-I feel very good about myself when I've written a lot of code that works. This is very important to me and gives me a lot of confidence. After all, when it works, I forget about how long my code is. Oh, my God, it was so childish.
If you want to write code that is more maintainable, simple, and error-free, it's best to keep it as concise and short as possible. The more concise the code, the easier it will be to test separately.
This is especially important if you prefer the functional programming paradigm. It is common sense that a function should do one thing well.
After reading the above, do you have any further understanding of the 7 JavaScript excellent practices? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.