The Wayback Machine - https://web.archive.org/web/20111012004527/http://www.webreference.com/programming/javascript/objects/

spacer

home / programming / javascript / objects current pageTo page 2
[next]

How To Create Unique Automatic JavaScript Objects

Developer News
Eclipse Helios Update Brings New PHP Tools
Internet Explorer 9 Ups Standards Support
JBoss Portal 5 Release Easier to Use

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:


home / programming / javascript / objects current pageTo page 2
[next]

Internet.com
The Network for Technology Professionals

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Flashmaps' DynamicLocator: Interactive Maps for Small Areas · Flashmaps' AreaSelector: Interactive Maps for Wide Areas · The DB Mapper: Interactive Street-level Maps of U.S. and Canada
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Vocalocity launches telephony/app integrations for Desktop · How to Reanimate Dead Spots in Wi-Fi Networks · PC Buyer's Guide for Gaming Enthusiasts

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

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