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
Facebook Wants to Power Web-Wide Apps
OpenSolaris to Support Facebook, OpenSocial
Sun Takes a Shine to Linux in New Web Stack

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]



JupiterOnlineMedia

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 >
Simple Comments Release Notes: v.960 · Adding Client Capabilities to Server Controls Using the ASP.NET AJAX Control Toolkit · How to Create an Ajax Autocomplete Text Field: Part 10
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Data Corruption: Dedupe's Achilles Heel · AccessLine Launches SOHO VoIP Product with Costco · Cisco to Acquire Pure Networks

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

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