How to create unique automatic JavaScript objects (1/2) | WebReference

How to create unique automatic JavaScript objects (1/2)

current pageTo page 2
[next]

How To Create Unique Automatic JavaScript Objects

By Philip Chalmers.

What this article is about

Here's a requirement from a recent project of mine--I hope you will find the solution interesting and useful:

The solution

The easiest way to explain it is by an example which shows you the main points of the code. I've line-numbered the code so it's easy to refer to in the explanation.

In the external file which contains the object type definition:

1   function myObjectType () {
2     if (myObjectType._pcOTinstance)
3       return myObjectType._pcOTinstance;
4     this.property1 = 'a';  // etc.
5   }
6   myObjectType._pcOTinstance = new myObjectType();

Line 6 creates an instance as soon as the external JS file is read. I'll explain about myObjectType._pcOTinstance on the next page.

When line 6 calls the constructor, myObjectType._pcOTinstance does not exist. So the constructor drops through to line 4, initializes the new instance's properties and returns a reference to it in the normal way. Hence the code in the external JS file creates one instance before anything else gets the chance to do so.

When another script uses the constructor, for example

var myInstance = new myObjectType();

the property myObjectType._pcOTinstance exists and the constructor returns a reference to the instance created by line 6 in the external JS file. No new instance is created--or more probably an instance is created (with no properties) but then destroyed immediately because nothing references it.

The line order is very important:


current pageTo page 2
[next]

Created: November 7, 2002
Revised: November 7, 2002

URL: https://webreference.com/programming/javascript/objects/