Prototypes in JavaScript

JavaScript is a prototypical based language. In JavaScript objects are pairs of keys and values and these keys are Strings. Rather than keys and values, JavaScript objects have one another attribute called prototype which is a pointer to another objects . prototype property allows you to add properties and methods to an object.

 In regular form We can add a property to an object using Object.defineProperty like this:

  1. var obj = new Object.create(null);
  2. Object.defineProperties(obj, 'Name', { age: "24", propertyIsEnumerable: true });
  3.  

But in inheritance, JavaScript only has one construct: objects and each object has an internal link to another object called prototype. It is a prebuilt object that simplifies the process of adding custom properties and methods to all instances of an object. You can add a prototype to an existing function:

  1. function Person(name, family) {
  2.     this.name = name;
  3.     this.family = family;
  4. }
  5.  
  6. var obj = new Person("ehsan", "Ghanbari");
  7. obj.prototype.age = "23";

Functions can be used to create class-like functionality in JavaScript; and all functions have a prototype property. Prototype is actually an instance of an object and every function in JavaScript has one whether you use it or not(like constructor in C#). Here is an another example of using prototype:

  1. function Car(color,model) {
  2.     this.color = color;
  3.     this.model = model;
  4. }
  5. Car.prototype.manufacturer = 'hunda';
  6.  
  7. var santafe = new Car("white", "new");

 

Read more:

  1. http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

 


Tags: JavaScript


comments powered by Disqus