JavaScript's single-case combat

Source: Internet
Author: User
Tags instance method

I. Overview

The so-called Singleton pattern, as the name implies, is only one instance of a class.

So, when we create an instance, we have to determine if it already exists, and if it already exists, return to the existing instance, without creating one ( singleton mode, the core is a class with only one instance If it does not exist, create this instance.

Well, the core idea of the singleton pattern and the creation process are largely clear, so let's start by looking at how it's done in the JavaScript world.

Second, actual combat one

The core idea: Use the scope of JavaScript to form a closure, so that you can create a private variable (assuming we name the private variable instance), and then assign the created instance to the private variable instance OK. Whenever you want to create an instance of this class, first determine if instance has referenced an existing instance, if there is no reference, that is, the class is not created, so creates an instance and assigns it to instance; If instance already has a reference, an instance of that class already exists. So no need to create any more, just use this instance to be OK.

The first step: perform anonymous functions to prevent namespace contamination. In an anonymous function, first define the above mentioned private variable instance and a class. For this class, I assume that it has a name (name) and an age of two attribute fields and a party that outputs their names (DisplayInfo) ha.

' Use strict 'varSingletonaccepter = (function(){    //By default, instance is given null    varInstance =NULL; //class: Supposeclass    functionSupposeclass (args) {varargs = args | | {};  This. Name = Args.name | | ' Monkey ';  This. Age = Args.age | | 24;    }; Supposeclass.prototype={constructor:supposeclass, DisplayInfo:function() {Console.log (' Name: ' + This. Name + ' Age: ' + This. Age); }    };}) ();

The second step: using the return + object literal, we want to, outward exposure to the east, thrown outward.

As follows:

return {    // class name    : ' Supposeclass '    ,// Create an instance method of the class    function(args) {        // Use private variable instance to implement Singleton mode        if  null  ) {            new  supposeclass (args);        }         return instance;    }};

Finally, the code that merges the second step in the first step forms a singleton pattern.

As follows:

' Use strict 'varSingletonaccepter = (function(){    //By default, instance is given null    varInstance =NULL; //class: Supposeclass    functionSupposeclass (args) {varargs = args | | {};  This. Name = Args.name | | ' Monkey ';  This. Age = Args.age | | 24;    }; Supposeclass.prototype={constructor:supposeclass, DisplayInfo:function() {Console.log (' Name: ' + This. Name + ' Age: ' + This. Age);    }    }; return {        //the name of the className: ' Supposeclass ',        //to create an instance method of a classGetInstance:function(args) {//using private variable instance to implement Singleton mode            if(Instance = = =NULL) {instance=NewSupposeclass (args); }            returninstance; }    };}) ();

Next, Let's examine this single pattern of writing. In the above code, add Console.log to the class Supposeclass, and if only one instance of it is created, then only one log will be printed.
Modify the code as follows:

' Use strict 'varSingletonaccepter = (function(){    varInstance =NULL; functionSupposeclass (args) {varargs = args | | {};  This. Name = Args.name | | ' Monkey ';  This. Age = Args.age | | 24; //Test Single-case modeConsole.log (' This is created! ');    }; Supposeclass.prototype={constructor:supposeclass, DisplayInfo:function() {Console.log (' Name: ' + This. Name + ' Age: ' + This. Age);    }    }; return{name:' Supposeclass ', getinstance:function(args) {if(Instance = = =NULL) {instance=NewSupposeclass (args); }            returninstance; }    };}) ();

Call two times getinstance method to see how several records are printed

Singletonaccepter.getinstance (); Singletonaccepter.getinstance ();

Execute the code and open Chrome as follows:

The identification is complete, only one instance at a time.

Third, the actual combat two

idea: use attributes to determine if an instance already exists.
What do you mean?
In the world of JavaScript, the class (function) is not an object, so give it an attribute instance, which refers to the created instance, by judging whether instance has referenced the created instance.

As follows:

functionSingletonaccepter (args) {//determine if an instance of Universe.instance already exists    if(typeofSingletonaccepter.instance = = = ' object '){        returnsingletonaccepter.instance; }     This. Name = Args.name | | ' Monkey ';  This. Age = Args.age | | 24; Singletonaccepter.instance= This;}; Singletonaccepter.prototype={constructor:singletonaccepter, DisplayInfo:function() {Console.log (' Name: ' + This. Name + ' Age: ' + This. Age); }};
Four, the actual combat three

In the JavaScript world, this is the referenced object.
Remember how JavaScript created objects from new?
New
  1 . Create a new object, the type of this object when object;
  2, the object of the __proto__ hidden pointer to the prototype prototype;
  3, executes the constructor function, when this is mentioned, represents the newly created object;
  4 . Returns the newly created object.
  Note: If you return at the end, then return is a basic type, such as 3, is invalid; otherwise, the reference type is returned.


Notice the 3rd?

When new, this represents the newly created object. So, we can use closures to declare a variable instance in the class to refer to the created instance. Then rewrite the class, OK.

As follows:

functionSingletonaccepter (args) {varInstance =NULL; varargs = args | | {};  This. Name = Args.name | | ' Monkey ';  This. Age = Args.age | | 24; //The instance created by the instance reference is thisInstance = This; //overriding ConstructorsSingletonaccepter =function(){        returninstance; }};singletonaccepter.prototype={constructor:singletonaccepter, DisplayInfo:function() {Console.log (' Name: ' + This. Name + ' Age: ' + This. Age); }};

JavaScript's single-case combat

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.