Journey through JavaScript design patterns

Introduction to design Patterns

In daily development, we all pay much attention to development skills, good development skills can be twice the result of half the effort to solve the current problem.

So how do these skills come about?

After constantly stepping on pits, solving bugs, and summarizing some solutions to the corresponding problems, this is the so-called skills.

Speaking of design patterns, we often use them at the beginning of everyday life, but you don’t know the name of the design pattern for the solution you are using.

Learn the power of design patterns

In software design, patterns are excellent solutions that have been proven by a number of real-world projects. Programmers who are familiar with these patterns will naturally conditioned their understanding of certain patterns. When the right scenario appears, you can quickly find the corresponding pattern to deal with the current problem.

The singleton pattern

Definition: Ensures that a class has only one instance and that it is globally accessible.

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

Because it satisfies two points of the singleton pattern:

  • Global variables created are unique
  • It has global access to the variable instance
// login.js
var loginInfo = {
  username: ' '.    token: ' '..}    //login.vue  import logins from './login.js'  logins.name = this.username Copy the code

However, it also has the disadvantage of causing namespace pollution.

Too many global variables will overwrite the previously defined global variables, which may cause unnecessary bugs.

How do you deal with namespace contamination?

How do you deal with that?

  • 1. Use namespaces
  • 2. Encapsulate private variables with closures

The namespace

Object arguments of the form:

// login.js
export default var loginInfo = {
    names:' ' ,
    token: ' '.    setName: function (name) {
 this.names = name  },  getName: function () {  return this.name  } }   //login.vue import logins from './login.js'  logins.token = this.token Copy the code

Use closures to encapsulate private variables

Encapsulate some variables inside closures, exposing only interfaces to communicate with the outside world.

Internally defined private variables are inaccessible to the outside world, thus avoiding global command contamination.

var user = (function () {
    // the outside world cannot access _name _age
    var _name = 'Joe'.        _age = 22;
    
 return {  // This is reserved for external communication  getUserInfo: function () {  console.log(The name is:${_name}, age:${_age}`)  }  } }) () user.getUserInfo() Copy the code

Generic lazy singleton pattern

In the case of this execution, the step/DOM is performed.

Advantages: Saves performance.

Scenario 1

Sometimes, such as the login popover, it will render the entire DOM of the page while loading the home page. If the home page DOM has a lot of content, the loading speed will be correspondingly slow, many of which do not require DOM rendering in advance.

In this case, the lazy singleton mode can be used to solve this problem. For example, the DOM of the login popover will be created only after the login button is clicked, and the click status will be recorded. If the DOM needs to be opened next time, just change the display property of the STYLE of the DOM. This saves page load time and improves page performance.

// Define the global generic singleton pattern
var getSingle = function (fn) {
    var result;
    return function () {
        return result || (result = fn.apply(this.arguments));
 } }  // Create a login window var createLoginLayer = function() {  var div = document.createElement('div')  div.innerHTML = 'Login box'  div.style.display = 'none'  document.body.appendChild(div)  return div }  // Create a singleton login box var createSingleLoginLayer = getSingle(createLoginLayer);  document.getElementById('btn').onclick = (a)= > {  // Get the login box returned in singleton mode  var loginLayer = createSingleLoginLayer();  // Change the style  loginLayer.style.display = 'block' } Copy the code
Scenario 2

Create a unique IFrame to load third-party pages

var createSingleIframe =  getSingle( function() {
    var iframe = document.createElement('iframe');
    document.body.appendChild(iframe)
    return iframe
})
 document.getElementById('redirect').onclick = (a)= > {  var iframeLayer = createSingleIframe();  iframeLayer.src = 'http://www.baidu.com' } Copy the code

This article is formatted using 👉 MDnice

The resources

<<JavaScript Design Patterns and Development Practices >>



If the content of this article is wrong, you are welcome to correct, learn 😆