Ehsan Ghanbari

Experience, DotNet, Solutions

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

 

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
How to query over Icollection<> of a type with linq
What's the DDD-lite?
comments powered by Disqus