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

Learn JavaScript design patterns - singleton pattern_javascript skills

WBOY
Release: 2016-05-16 15:19:16
Original
1074 people have browsed it

1. Definition

Guarantee that a class has only one instance and provide a global access point to it.
When you click the login button, a login floating window appears on the page. This login floating window is unique. No matter how many times you click the login button, this floating window will only be created once. Then this login floating window is suitable for use as a singleton. pattern to create.

2. Implementation Principle

It is not complicated to implement a singleton. Use a variable to mark whether an object has been created for a certain class. If so, the previously created object will be returned directly the next time you get an instance of the class.

3. Fake Singleton

Global variables are not in singleton mode, but in JavaScript development, we often use global variables as singletons.

var a = {};

Copy after login

Reduce naming pollution caused by global variables
(1) Use namespace

var namespace1 = {
  a: function(){},
  b: 2
}
Copy after login

(2) Use closures to encapsulate private variables

var user = (function() {
  var _name = 'lee',
    _age = '25';
  return {
    getUserInfo: function() {
      return _name + ":" + _age;
    }
  };
})();
Copy after login

4. Lazy singleton: create object instances only when needed

var getSingle = function(fn) {
  var result;
  return function() {
    return result || (result = fn.apply(this, arguments));
  };
};

// 测试
function testSingle(){}
getSingle(testSingle)() === getSingle(testSingle)();  // true

Copy after login

5. Supplement:

(1) Lazy loading

var lazyload = function() {
  console.log(1);
  lazyload = function() {
    console.log(2);
  }
  return lazyload();
}

lazyload();
Copy after login

(2) Preloading

var preload = (function() {
  console.log(1);
  preload = function() {
    console.log(2);
  };
  return preload;
})();

preload();
Copy after login

I hope this article will be helpful to everyone learning JavaScript programming.

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!