Learning JavaScript Design Patterns by single case pattern _javascript techniques

Source: Internet
Author: User

I. Definition

Guarantees that a class has only one instance and provides a global access point to access it.
When you click the login button, a landing floating window appears on the page, the Landing window is unique, no matter how many clicks the login button, the floating window will only be created once, then the landing window is suitable for the use of single case mode to create.

Ii. Principle of realization

To implement a singleton is not complicated, a variable is used to flag whether an object has already been created for a class, and if so, the object created earlier is returned directly the next time an instance of the class is obtained.

Third, the false single case

Global variables are not a single case pattern, but in JavaScript development we often use global variables as a single example.

var a = {};

Reduce the naming pollution caused by global variables
(1) using namespaces

var Namespace1 = {
  a:function () {},
  b:2
}

(2) using closures to encapsulate private variables

var user = (function () {
  var _name = ' Lee ',
    _age = ';
  return {
    getuserinfo:function () {return
      _name + ":" + _age;}}
) ();

Iv. inert Singleton: To create an object instance when needed

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

Test
function TestSingle () {}
Getsingle (testsingle) () = = Getsingle (testsingle) ();  True

V. Add:

(1) Lazy loading

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

Lazyload ();

(2) Pre-loading

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

Preload ();

I hope this article will help you learn about JavaScript programming.

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.