spacer
home / programming / javascript / gr / column9 / 1 current pageTo page 2To page 3
[next]

Web Project Manager
Aquent
US-PA-Collegeville

Justtechjobs.com Post A Job | Post A Resume
Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

How to Use JavaScript++

This article was inspired by some work I did for a web site a few years ago. One problem I encountered was that many of the core features of JavaScript that I wanted to use were only supported in the latest browsers.

 

At the time, IE6.0 was just being released and my requirements were to design the website to support browsers as old as IE4.0 and Netscape 4.7. In a landscape as rocky and variable as JavaScript with the existing browsers the maxim is often: “write once, pray it runs on most browsers.”

 

The usual mantra is “program to the lowest common denominator” but the problem was that these browsers had little in common. It would be nice to believe that most people have upgrated to the latest browsers, but in reality, there are many old browsers still surfing the net. A quick visit to www.thecounter.com indicates that roughly 80% of users are using the latest browsers, 20% are not. That’s a lot of users. To solve the problem, I had to plug the holes, factor up the denominators or – add something to JavaScript.

Some Background First

To the JavaScript developer, JavaScript objects can be thought of as an amorphous blob of un-typed properties. Every detail of the object is stored in this manner, including member variables, constructors, methods and even array items.

 

JavaScript is most certainly object based; you can’t go far in JavaScript without bumping into an object of some kind. There are a fair number of different types predefined in the language; Array objects store items indexed by numbers and come with some useful methods, Date objects provide useful methods for measuring time and so on. Even numbers are sometimes converted into objects when necessary.

 

JavaScript ‘Classes’ are based on a special property called prototype. The prototype contains predefined properties and functions that are common to all instances of the particular class. Prototypes are held in a chain for each object and this offers a type of inheritance. A Date object automatically has all the properties and methods defined in Date.prototype as well as those defined in Object.prototype.

Now for the details…

Now that we know a bit about JavaScript objects, prototypes and properties, let’s have a look at how we can solve the original problem stated above.

The undefined property

A relatively recent addition to JavaScript is the undefined property. It's useful when you want to test whether a variable has been initialized or not.

 

var a;

if ( a == undefined ) a = "some value";

 

The trouble with this code is that if JavaScript doesn’t support the undefined property, the code above will fail with an error.

The solution is to simply declare the undefined property in the code…

 

var undefined;

 

This variable will be added to the Global object and since it is not given any value, its value will be undefined. You don’t need to worry about the newer browsers that already support the undefined property, this code replaces the predefined version and behaves in the same way.

New Array methods

Arrays have been supported in JavaScript for some time, however a few new methods have been recently added, including push, pop, shift, splice and unshift.

We'll start with push and pop…

 

// toNumber() – a convenience function to convert a variable to a number.

Array.prototype.toNumber = function(x)

{

   // return the numerical value of x only if it is completely numeric

   switch ( typeof(x) )

   {

      case "number":

         return x;

      case "string":

         var n = parseInt(x);

         if ( !isNaN(n) && ("A"+n == "A"+x) ) return n;

         break;

      default:

         break;

   }

   // otherwise return undefined

}

// highestIndex() – convenience function to return the highest numerical index

// in an array, or undefined if none are found.

Array.prototype.highestIndex = function()

{

   var m;

   // find the highest array index and add a next one

   for ( var i in this )

   {

      var n = this.toNumber(i);

      if ( (n != undefined) && ((m == undefined) || (n > m) ) ) m = n;

   }

   return m;

}

// only add a push method if Array doesn’t already have one

if ( !Array.prototype.push ) Array.prototype.push = function()

{

   var m = this.highestIndex();

   if ( m == undefined ) m = -1;

   for ( var i = 0; i < arguments.length; i++ )

      this[++m]=arguments[i];

}

// only add a pop method if Array doesn’t already have one

if ( !Array.prototype.pop ) Array.prototype.pop = function()

{

   var m = this.highestIndex();

   var v;

   if ( m != undefined )

   {

      v = this[m];

      delete this[m];

   }

   return v;

}

 

home / programming / javascript / gr / column9 / 1 current pageTo page 2To page 3
[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

Whitepapers and eBooks

Symantec Whitepaper: Converging System and Data Protection for Complete Disaster Recovery
Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
  Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Symantec Whitepaper: Comprehensive Backup and Recovery of VMware Virtual Infrastructure
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Fixing MySQL Replication · Firewall Guide: First Steps to Securing the Enterprise · VoxOx Tames the Tumultuous Communications Tangle

Created: March 27, 2003
Revised: September 29, 2004

URL: http://webreference.com/programming/javascript/gr/column9/1