Today, when I was working on a project, I encountered the situation where I needed to create a JavaScript object. So Bing an article written by a foreigner about creating JavaScript objects, and then read it and typed the code. I feel the method is pretty good, so I will share it with you here.
1. Create objects using functions:
The code copy is as follows:
//Define the object
function Animal(type)
{
this.name="";
this.type=type;
this.introduction=function(){
return "My name is: "+this.name+", I belong to "+this.type;
}
}
var animal=new Animal("poultry"); //Instantiate the object we created above
animal.name="Xiaohong";
alert(animal.introduction()); //Call its introduction function (at this time, the page will pop up: My name is Xiaohong, I belong to poultry);
Everyone must be familiar with this method. However, using this method can cause performance losses. Here, we instantiate the object through the new key. In fact, the key to new is to do two things. 1. An anonymous method 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.
The code copy is as follows:
//Define the object
var Book=
{
name: "Dream of Red Mansions",
type: "Literary Works",
getAuthor:function()
{
return :"I am Cao Xueqin's child!";
}
}
alert(Book.GetAuthor()); //Call the object method, and the page will appear: I am Cao Xueqin's child.
Book.name="slam dunk"; //Modify object properties
alert(Book.name); //At this time, the page will pop up: Slam dunk
I believe that when you see the code, you should understand why this method is more efficient. Because, it is equivalent to defining a JavaScript global variable. We can use it directly without instantiating it. But, it looks weird. Then, the solution is here. Let’s take a look at the third method.
3. Singleton using a function:
Translated into singleton mode may not be appropriate. Let's look at the code first:
The code copy is as follows:
//Define the object
var Gender=new function()
{
this.type="Girls";
this.speaking=function()
{
return "I am"+this.type;
}
}
alert(Gender.speaking();) //The page will appear when using the object: I am a girl.
If you look at this code, is it very similar to our method? However, it can work like Method One. Method 1: Use an object once, and you need to create an object once. This method can be used permanently by creating an object once. Therefore, this method is very similar to the singleton pattern in the design pattern.