Create and invoke a collection of methods for the JavaScript object

  • 2020-05-09 18:09:20
  • OfStack

Today, while working on a project, I encountered a situation where I needed to create an JavaScript object. So Bing wrote a laowai article about creating JavaScript objects in three different ways, and then typed the code again. Feel the method is good, here to share with you 1.

  1. Create objects with functions:


// 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=" The little red ";
      alert(animal.introduction());      // Call it the introduction function ( At this point, the page will pop up: my name is Xiao hong, I belong poultry );

This method must be familiar to all of you. However, there is a performance penalty to using this approach. In this case, we instantiate the object through the new key child. Actually, new does two things. 1, an anonymous method (Animal) is defined. 2. Call it. This is not as efficient as the method we will describe next.

2. Use object literals (object literals):

        I don't know if the translation is correct, I will tell you the address of the original text later, you can read the original if you are interested.


// Define the object
    var Book=
    {
          name:" A 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 point, the page will pop up: Slam Dunk

    I think you can see why this method is more efficient when you look at the code. Because, it is equivalent to defining an JavaScript global variable. We can just use it, we don't need to instantiate it. But, it looks weird. So here's the solution. Let's look at the third way.

3. Singleton mode (Singleton using a function) :

The translation of         into singleton mode may not be appropriate. Let's look at the code first:


// Define the object
    var  Gender=new function()
 {
       this.type=" The girl ";
      this.speaking=function()
{
      return " I am a "+this.type;
}
}
     alert(Gender.speaking();)   // Using the object   The page will appear : I'm a girl.

If you look at this code,  , does it look like our method 1? However, it works like method 1. Method 1, if you take an object once, you create an object once. This method, create the object once, can be used permanently. So, this approach is very similar to the singleton pattern in the design pattern.


Related articles: