Find jobs | Jobseekers
Employer login
About us Sitemap of www.CareerRide.com Sitemap FAQ related with www.CareerRide.com FAQ Click here to Contact us Contact
       
Submit Resume Free ! | Access Resume Free !
Home Career Services Resume Services Interview questions Articles Books

How to work with JavaScript prototypes


Book Excerpt: Object-Oriented JavaScript

>What encapsulation, inheritance, and polymorphism mean
>How JavaScript functions work
>How to use anonymous functions and closures
>How to read a class diagram, and implement it using JavaScript
>How to work with JavaScript prototypes
>How the execution context and scope affect the output of JavaScript functions
>How to implement inheritance using closures and prototypes
>What JSON is, and what a JSON structure looks like
This chapter excerpt from Microsoft AJAX Library Essentials by Cristian Darie, Bogdan Brinzarea, is printed with permission from Packt Publishing, Copyright 2007.

Prototypes 

You learned earlier that in JavaScript you should defi ne "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 refl ects quite well the behavior of classes in C#, although the core mechanism and the specifi c 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:

//Table class
function Table (rows, columns)
{
      // save parameter values to class properties
      this.rows = rows;
      this.columns = columns;
}

//Table.getCellCount returns the number of table cells
Table.prototype.getCellCount = function()
{
    return this.rows * this.columns;
}; 

Related Links
>Object Oriented Programming Interview Questions

Today's Hot Jobs
C++  SQL Server
.NET  Java  Oracle
Finance  Marketing
Seekers  Employers
Copyright © 2008 CareerRide.com. All rights reserved.