How to create unique automatic JavaScript objects (1/2)
[next] |
How To Create Unique Automatic JavaScript Objects
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:
- create a JavaScript object type definition which can be used in many pages--so it's in an external JavaScript file.
- create one and only one instance per Web page / frame.
- make the same instance available to other scripts, without requiring the other scripts to use a particular variable name and without creating any new global names (I think I'm slightly paranoid about the risk of name conflicts).
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:
- Line 6 should immediately follow the constructor function, in case you package an object like this with some other code which uses the constructor to get a reference to the object.
- Lines 2 and 3 must be the first statement in the constructor, to make sure that it returns a reference to the automatically-created instance on every call after the one in line 6.
[next] |
Created: November 7, 2002
Revised: November 7, 2002
URL: https://webreference.com/programming/javascript/objects/