How to work with JavaScript prototypes

          

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 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:

//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
Test your Oops knowledge with our multiple choice questions!
Object Oriented Programming Interview Questions



Write your comment - Share Knowledge and Experience


Latest placement tests
Latest links
 
Latest MCQs
» General awareness - Banking » ASP.NET » PL/SQL » Mechanical Engineering
» IAS Prelims GS » Java » Programming Language » Electrical Engineering
» English » C++ » Software Engineering » Electronic Engineering
» Quantitative Aptitude » Oracle » English » Finance
Home | About us | Sitemap | Contact us | We are hiring