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

 

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. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus