Two js Singleton Modes

Source: Internet
Author: User

Solution 1: using the two functions of closures, You can flexibly read internal variables. Second, you can keep these variables in the memory.

Copy codeThe Code is as follows:
// Solution 1
Var SingletonTester = (function (){
// Singleton Method
Function Singleton (args ){
Var args = args || {};
This. name = 'singletontester'; // The external attribute of the method. The other method is to return the object.
This. pointX = args. pointX | 6;
This. pointY = args. pointY | 10;
}

// Singleton instance
Var instance;

// Return object
Return {
Name: 'singletontester ',

GetInstance: function (args ){
If (instance === undefined ){
Instance = new Singleton (args );
}
Return instance;
}
};
}) (); // Directly execute this method

// Test
Var test = SingletonTester. getInstance ({pointX: 5 });
Console. log (test. pointX );

Solution 2:

Copy codeThe Code is as follows:
// Solution 2
Function Universe (){
// Determine whether an instance exists
If (typeof Universe. instance === 'object '){
Return Universe. instance;
}

// Other content
This. start_time = 0;
This. bang = "Big ";

// Cache
Universe. instance = this;

// Implicitly return this
}

// Test
Var uni = new Universe ();
Var uni2 = new Universe ();
Console. log (uni === uni2); // true

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.