spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

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

How To Create Unique Automatic JavaScript Objects

Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

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.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

webref The latest from WebReference.com Browse >
Working with the DOM Stylesheets Collection · Administering RBAC in PHP 5 CMS Framework · xref: Automatic Cross Referencing Script
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Combine BottomCount() with Other MDX Functions to Add Sophistication · Creating a Daemon with Python · The Coming Voice-over-WiMAX Revolution

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

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