spacer

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

home / programming / javascript / professional / chap3 / 3 123
[previous] [next]
Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

Professional JavaScript

Inheritance via a Shared Class Object

The simplest form of inheritance in JavaScript is for the object instance for the derived class to collect the information it inherits from the class definition object for its base class. Therefore this is a case of mixing up instance and class objects.

function Polygon() { this.edges = 8; // octogons are the default this.regular = false; // sides needn't be all the same this.area = new Function (...) // some hard mathematics } function Rectangle(top_len, side_len) { this.edges = 4; this.top = top_len; this.side = side_len; this.area = new Function("return this.top*this.sides"); } Rectangle.prototype = new Polygon;

This example has two object constructors: the two functions. Since functions are objects in JavaScript, there are two new objects as well. There is also a third new object. It has been added to the Rectangle function object's prototype chain in the last line, and that is the only place it is accessible. That object can be thought of as a class definition object, because it is only really used at object creation time, and there is only ever one of it.

To create a new Rectangle, use this code:

var box = new Rectangle(8,3);

Afterwards the object's properties are:

box.edges = 4 // overrides Polygon box.top = 8 box.side = 3 box.area = Function("return this.top*this.sides"); box.regular=false // from Polygon

The benefits of this approach are:

  • Simplicity - inheritance is achieved with the single extra statement Rectangle.prototype = ..
  • Properties in the derived objects correctly override base object properties.
  • Information in the base object is not duplicated; it is looked up via the prototype chain.
  • If you modify the base object, which is acting like a class definition, then all of the derived objects will see the change.
  • Any amount of inheritance hierarchy is possible – Square objects could have Rectangles in their prototype chain and they would benefit from the Polygon class object instance as well.

However, this approach does have drawbacks. The problems mostly revolve around the fact that there is only one prototype chain for the Rectangle constructor, and it is shared between all Rectangle objects that are created. So any Rectangle object that modifies properties of the base class changes them for all Rectangle objects.

  • Modifying the base class object's properties doesn't just affect the current object; it affects all objects of this type that are hanging around.
  • The base class object's constructor (Polygon() in this case) can't have any arguments; or at least it must be able to survive without being passed any arguments.

You can work around the first problem by overriding all the base class objects properties in the derived instance object constructor (Rectangle). However, if you do that, overriding everything, one wonders why bother use inheritance at all – you might as well just have a separate object type.

Sometimes you do want properties in the base class to be updated by every derived instance ('static class variables'). Here's an example:

function Counter() { this.total=0; } function StockItem() { this.total++; } StockItem.prototype = new Counter; var biscuits = new StockItem; // total = 1 var coffee = new StockItem; // total = 2

Every object contributes something to the shared property. In the example above, this property is a total of the objects currently existing (this simple example doesn't correctly decrease the total if objects go away).

Finally, if you can avoid changing any state in the base class object, then the approach we've outlined here can still be quite useful. You could put a store of constant data and methods in it that will be usable by all derived instance objects. The methods in the base class object can refer to properties in derived instances as well. Here's an example:

function Base(v) { if (arguments.length != 0) this.value = v; this.double_up = new Function ("this.value*=2;") } function Derived(v) {this.value = v;} Derived.prototype = new Base; var obj = new Derived(5); obj.double_up(); // this.value = 10

Notice how in this example the base class object uses, but may never define the value property. In that case, the derived instance object's value property will be doubled. The 'if' condition in the base class object is only true if the Base() function is used as a simple constructor, not when inheritance is at work. For C++ and Java experts: this mechanism works well for abstract base classes.

home / programming / javascript / professional / chap3 / 3 123
[previous] [next]

Copyright 1999 (1st Edition) and 2001 (2nd Edition) Wrox Press Ltd. and

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
Microsoft PDF: Top 10 Reasons to Move to Server Virtualization with Hyper-V
Microsoft PDF: Six Reasons Why Microsoft's Hyper-V Will Overtake Vmware
Microsoft Step-by-Step Guide: Hyper-V and Failover Clustering
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Microsoft PDF: Top 11 Reasons to Upgrade to Windows Server 2008
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: February 12, 2001
Revised: February 12, 2001


URL: http://webreference.com/programming/javascript/professional/chap3/