While working on a project today, I encountered a situation where I needed to create a JavaScript object. So I Bing an article written by a foreigner about three ways to create JavaScript objects, and then typed the code after reading it. I feel like the method is pretty good, so I’d like to share it with you here.
1. Use functions to create objects:
Everyone must be familiar with this method. However, using this method will cause a loss in performance. Here, we instantiate the object through the new key. In fact, the new key does two things. First, an anonymous method (Animal) is defined. 2. Call it. This is not as efficient as the method we will introduce next.
2. Use object literals:
I don’t know if the translation is correct. I will tell you the original address later. If you are interested, you can read the original text.
I believe everyone will understand why this method is more efficient after seeing the code. Because it is equivalent to defining a JavaScript global variable. We can use it directly without instantiating it. However, this looks weird. Well, here comes the solution. Let's take a look at the third method.
3. Singleton mode (Singleton using a function):
It may not be appropriate to translate it into singleton mode. Let’s look at the code first:
Look at this code, is it very similar to our method one? However, it works like method one. Method 1: Use the object once and create the object once. This method creates an object once and can use it permanently. Therefore, this approach is very similar to the singleton pattern in design patterns.