Saturday, April 8, 2017

JavaScript Protoypes

Prototype is a fundamental concept that every java-script developer should understand. Every java script object has a Prototype and Prototype is also a object.All java-script objects inherit their properties and methods from prototype.by default prototype property is empty for every function.

prototype chain

Every object in Java-script has a prototype. When a messages reaches an object, JavaScript will attempt to find a property in that object first, if it cannot find it then the message will be sent to the object’s prototype and so on. This works just like single parent inheritance in a class based language.Prototype inheritance chain can go long but it is not god idea to make it long because if the chain is long it will be hard to identify and maintain the code. 

How to create a object 

An object can create using
  • object literals 
  • new key word
In java-script objects are variables that containing objects.

using Object Literals. 

These objects are considered to be Singleton.
var student={
    this:firstName=fName,
    this:lastName=lName,
    this:stdAge=age
}

Using New keyword.


var student=new Object();
student.firstName='John';
student.lastName='little';
student.stdAge=10;
creating objects using above methods are limited in many situations.They only create single object.Solution for that situations is using object constructors.we can create a prototype using the same way we create constructor function.
function student(fName,lName,age){
    this.firstName=fName;
    this.lastName=lName;
    this.stdAge=age;
}
//creating object student1
var student1=new student('little','John',20);
var student2=new student('Robin','hood',20);
In here we can create objects as many as we want with student type.This is the standard way to create and object.  

Adding properties to object.

//adding property GPA to student1 object
student1.GPA=3.5;
the property GPA is added to student1 not to student2. 

Adding method to object.

//adding method name to student1 object
student1.name = function () {
    return this.firstName + " " + this.lastName;
};
Here 'this' belong to student1.

Adding property to prototype

student.nationality = "Sinhala";
We cannot add property to prototype/constructor function the same we add property to a object.We need to use prototype keyword to add property to a prototype.if not, result will be undefined.
student.prototype.nationality = "Sinhala";
Here nationality is adding to student.so both student1 and student2 objects have nationality property.


Adding method to prototype. 

function student(fName,lName,age){
    this.firstName=fName;
    this.lastName=lName;
    this.stdAge=age;
    this.name = function() {return this.firstName + " " + this.lastName;};
}
now here we can directly call student1.name() to get full name.

References : w3schools

No comments:

Post a Comment