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:
//Define the object
function Animal(type)
{
="";
=type;
=function(){
return "My name is: "++", I belong to "+;
}
}
var animal=new Animal("poultry"); //Instantiate the object we created above
="Xiaohong";
alert(()); //Calling 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.
//Define the object
var Book=
{
name: "Dream of Red Mansions",
type: "Literary work",
getAuthor:function()
{
return :"I am Cao Xueqin's child!";
}
}
alert(()); //Calling the object method, the page will appear: I am Cao Xueqin's child.
="Slam Dunk"; //Modify object properties
alert(); //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:
//Define the object
var Gender=new function()
{
="Girls";
=function()
{
return "I am"+;
}
}
alert(();) //User object The page will appear: I am a girl.
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.