Exforsys.com
 
Home Tutorials Microsoft AJAX
 

Microsoft AJAX Library - Creating Object Members on the Fly

 

Prototypes

Page 2 of 2


Prototypes

You learned earlier that in JavaScript you should define "class methods" outside the body of the "class", in order to prevent their multiplication for each instantiated object. Prototyping is a JavaScript language feature that allows attaching functions and properties to the "blueprint" of a function.



When functions are added to a class (function) prototype, they are not replicated for each object of the class (function). This reflects quite well the behavior of classes in C#, although the core mechanism and the specific implementation details differ greatly. A few facts that you should keep in mind about prototypes are:


  • Every JavaScript function has a property named prototype. Adding members to the function's prototype is implemented by adding them to the prototype property of the function.
    .
  • Private variables of a function aren't accessible through functions added to its prototype.
    .
  • You can add members to a function's prototype at any time, but this won't affect objects that were already created. It will affect only any new ones.
    .
  • You can add members to a function's prototype only after the function itself has been defined.

The Table "class" from the previous example contains a "method" named getCellCount(). The following code creates the same class, but this time adding getCellCount() to its prototype:



Sample Code
  1. // Table class
  2. function Table (rows, columns)
  3. {
  4. // save parameter values to class properties
  5. this.rows = rows
  6. this.columns = columns
  7. }
  8. // Table.getCellCount returns the number of table cells
  9. Table.prototype.getCellCount = function()
  10. {
  11. return this.rows * this.columns
  12. }
Copyright exforsys.com






First Page: Microsoft AJAX Library - Creating Object Members on the Fly


Read Next: Microsoft AJAX Library - JavaScript Execution Context



 

 

Comments



Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 

Subscribe via RSS


Get Daily Updates via Subscribe to Exforsys Free Training via email


Get Latest Free Training Updates delivered directly to your Inbox...

Enter your email address:


 

Subscribe to Exforsys Free Training via RSS
 

 
Partners -  Privacy and Legal Policy -  Site News -  Contact   Sitemap  

Copyright © 2000 - 2010 exforsys.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape