Home > Web Front-end > JS Tutorial > body text

Two options for js singleton mode_javascript skills

WBOY
Release: 2016-05-16 17:19:18
Original
1043 people have browsed it

Option 1: Using the two functions of closure, the internal variables can be read flexibly, and the second is to keep these variables in the memory.

Copy code The code is as follows:

//Option 1
var SingletonTester = (function { Another way is to return the object
this.pointX = args.pointX || 6;
this.pointY = args.pointY || 10;
}

//Single instance
var instance;

//return object
return {
name: 'SingletonTester',

getInstance: function (args) {
                 if (instance = == undefined) {
                       instance = new Singleton(args);                                                                          
})(); //Execute this method directly

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




Option 2:


Copy code

The code is as follows:

// 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 labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!