Blog

Filter posts by Category Or Tag of the Blog section!

Prototypes in JavaScript

Friday, 27 December 2013

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

 

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

 

But in inheritance, JavaScript only has one construct: objects and each object has an internal link to another object called the 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:

 

function Person(name, family) {
    this.name = name;
    this.family = family;
}

var obj = new Person("ehsan", "Ghanbari");
obj.prototype.age = "23";

 

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

 

function Car(color,model) {
    this.color = color;
    this.model = model;
}
Car.prototype.manufacturer = 'hunda';

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

 

Category: Software

Tags: JavaScript

comments powered by Disqus