Home > Web Front-end > JS Tutorial > My Favorite JavaScript Design Pattern

My Favorite JavaScript Design Pattern

Christopher Nolan
Release: 2025-03-09 00:30:12
Original
601 people have browsed it

My Favorite JavaScript Design Pattern

My Favorite JavaScript Design Pattern

I thought it might be interesting to look at a JavaScript design pattern that I use a great deal. I settled on it gradually, over a period of time, absorbing and adapting influences from various sources, until reaching a pattern that offers the flexibility I need.

Let me show you an overview, and then look at how it comes together:

function MyScript(){}
(function()
{

  var THIS = this;

  function defined(x)
  {
    return typeof x != 'undefined';
  }

  this.ready = false;

  this.init = function(
  {
    this.ready = true;
  };

  this.doSomething = function()
  {
  };   

  var options = {
      x : 123,
      y : 'abc'
      };

  this.define = function(key, value)
  {
    if(defined(options[key]))
    {
      options[key] = value;
    }
  };

}).apply(MyScript);
Copy after login
Copy after login

As you can see from that sample code, the overall structure is a function literal:

(function()
{
  ...

})();
Copy after login
Copy after login

A function literal is essentially a self-executing scope, equivalent to defining a named function and then calling it immediately:

function doSomething()
{
  ...
}

doSomething();
Copy after login
Copy after login

I originally started using function literals for the sake of encapsulation—any script in any format can be wrapped in that enclosure, and it effectively “seals” it into a private scope, preventing it from conflicting with other scripts in the same scope, or with data in the global scope. The bracket-pair at the very end is what executes the scope, calling it just like any other function.

But if, instead of just calling it globally, the scope is executed using Function.apply, it can be made to execute in a specific, named scope which can then be referenced externally.

So by combining those two together—the creation of a named function, then the execution of a function literal into the scope of the named function—we end up with a single-use object that can form the basis of any script, while simulating the kind of inheritance that’s found in an object-oriented class.

The Beauty Within

Look at that first code example, and you can see what flexibility is offered by the structure of the enclosing scope. It’s nothing you can’t do in any function, of course, but by wrapping it up in this way we have a construct that can be associated with any named scope.

We can create multiple such constructs, and associate them all with the same scope, and then all of them will share their public data with each other.

But at the same time as sharing public data, each can define its own private data too. Here for example, at the very top of the script:

var THIS = this;
Copy after login

We’ve created a private variable called THIS which points to the function scope, and can be used within private functions to refer to it—exactly the same trick as going "self = this" to create a reference for inner scopes.

Other private variables, declared the same way, can share the uppercase convention if they define constant data (however declaration using const instead of var should be avoided, because it’s not well-supported).

Private functions can be used to provide internal utilities:

function MyScript(){}
(function()
{

  var THIS = this;

  function defined(x)
  {
    return typeof x != 'undefined';
  }

  this.ready = false;

  this.init = function(
  {
    this.ready = true;
  };

  this.doSomething = function()
  {
  };   

  var options = {
      x : 123,
      y : 'abc'
      };

  this.define = function(key, value)
  {
    if(defined(options[key]))
    {
      options[key] = value;
    }
  };

}).apply(MyScript);
Copy after login
Copy after login

Then we can create public methods and properties, accessible to other instances, and to the outside:

(function()
{
  ...

})();
Copy after login
Copy after login

We can also create privileged values—which are private, but publicly definable, in this case via the public define method; its arguments could be further validated according to the needs of the data:

function doSomething()
{
  ...
}

doSomething();
Copy after login
Copy after login

Wrapped Up!

All of these features are what makes the construct so useful to me. And it’s all wrapped up in a neat, self-executing singleton—a single-use object that’s easy to refer-to and integrate, and straightforward to use!

So what do you think? Is this a pattern that’s familiar to you, or do you have something else you like to use?

Thumbnail credit: superkimbo

note:Want more?

If you want to read more from James, subscribe to our weekly tech geek newsletter, Tech Times.

The above is the detailed content of My Favorite JavaScript Design Pattern. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template