The paper contains 2976 words and is expected to last 6 minutes
Source: Pexels
1. When writing constructors, add methods to.prototype
Based on my experience with JavaScript in my first two years, if you are new to JavaScript, this part may be unfamiliar to you.
(Keep in mind that this doesn’t apply to classes, because classes already have methods attached to their Prototypes.)
Here is an example of a constructor:
functionFrog(name, gender) {Copy the code
this.name= nameCopy the code
this.gender= genderCopy the code
}Copy the code
Frog.prototype.leap=function(feet) {Copy the code
console.log(`Leaping ${feet}ft into the air`)Copy the code
}Copy the code
Why not just append the LEAP method as in the following example?
functionFrog(name, gender) {Copy the code
this.name= nameCopy the code
this.gender= genderCopy the code
this.leap=function(feet) {Copy the code
console.log(`Leaping ${feet}ft into the air`)Copy the code
}Copy the code
}Copy the code
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 frogs (from this.leap = function() {… }), and you end up creating three separate copies. This is a problem because the LEAP method always stays the same and does not need to make its own copy on the instance.
This results in 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, frogs might have their own name and gender, so they are created at the instance level.
Here’s an example of a popular Request package using this approach (on GitHub).
2. Use the TypeScript
TypeScript is already widely used in the JavaScript community as a powerful defense against type safety and helps prevent errors.
Using TypeScript enables the compiler to detect potential errors and display warnings before code is run.
But that doesn’t go far enough to explain why TypeScript can be used in 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 a project is to be tackled seriously, tests must be used so that the application is more predictable, less error-prone, and flexible to future changes. In other words, if you’re going to build a project that will stand the test of time, there’s no better way to build tests throughout the code. The more testing you put into your code, the more confidence you’ll have in it once it’s in production.
What was the best part of the test? The ability to catch mistakes so they don’t show up — who wouldn’t want that? I’m sure I do. That’s why I wrote unit tests in my project.
Source: Pexels
4. When using json. parse or json. stringify, be sure to consider using try/catch
In JavaScript, when JSON is passed as input to json.parse, a properly formatted JSON is required as the first argument. If the format is incorrect, a JSON parsing error is displayed.
The danger from JSON parsing errors is that accepting invalid JSON causes the application to crash. Recently one of our Web projects failed because another built-in package did not install json.parse in a try/catch. The web page ends up dead, and because the JavaScript runtime is broken, it can’t be fixed unless the built-in package fixes it.
SyntaxError: Unexpected token }in JSON at position 107Copy the code
Valid JSON input should not always be expected, as it will receive strange characters such as “>”, which is quite common today.
5. Use the regular.type attribute to distinguish
It’s a great method, and it’s widely used. React developers may see this practice every day, especially when working with Redux.
Using a similar approach makes the development process infinitely easier, because it even keeps track of itself.
functioncreateSpecies(type, name, gender) {Copy the code
if (type= = ='frog') {Copy the code
returncreateFrog(name, gender)Copy the code
} elseif (type= = ='human') {Copy the code
returncreateHuman(name, gender)Copy the code
} elseif (type == undefined) {Copy the code
thrownewError('Cannot create a species with an unknown type')Copy the code
}Copy the code
}Copy the code
const myNewFrog =createSpecies('frog'.'sally'.'female')Copy the code
6. Use factory functions
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 leverage 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 a factory function?
The factory function makes it easy to generate object instances without involving the class or the new keyword.
This essentially means that they will eventually be treated as functions that can be used to combine objects, functions, and even Promise functions. This shows that you can mix and match factory functions to create an upgraded version of a factory function, and then continue to combine them with other functions or objects to create stronger factory functions. The possibilities are endless.
With that in mind, combine it with good code practices and it starts to shine.
Here is a simple example of a factory function:
functioncreateFrog(name) {Copy the code
const children = []Copy the code
return {Copy the code
addChild(frog) {Copy the code
children.push(frog)Copy the code
},Copy the code
}Copy the code
}Copy the code
const mikeTheFrog =createFrog('mike')Copy the code
When you use enough factory functions, you realize that factory functions are much more reusable than class constructors. This reduces the amount of code, reduces code refactoring time (because factory functions eventually return arbitrary objects), and reduces management time from one code to another.
Source: Pexels
7. Make functions as simple as possible
It is well known that in JavaScript it is possible to have large functions that do many things at once.
Novice programmers might find this a good thing — I felt pretty good about myself when I wrote large chunks of code that worked. This is very important to me and gives me a lot of confidence. It worked, after all, and I forgot how verbose my code was. Oh, my God, that was so childish.
If you want to write more maintainable, simple, error-less code, keep it as short as possible. The simpler the code, the easier it is to test individually.
This is especially important if you prefer the functional programming paradigm. It is common sense that functions that do one thing should do it well.
Hopefully it will be useful for you to get better JavaScript best practices.
Leave a comment like follow
We share the dry goods of AI learning and development. Welcome to pay attention to the “core reading technology” of AI vertical we-media on the whole platform.
(Add wechat: DXSXBB, join readers’ circle and discuss the freshest artificial intelligence technology.)