Friday, February 24, 2017

JavaScript Prototype

1.What is it ?


Every javascript object is inherited from another object called as the prototype object. Through the prototype object we can add properties and functions to an existing object. When ever an object is created, it will be automatically inherited from a prototype object which is specific to the created object.
  1. Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.
  2. Objects created with new Date() inherit the Date.prototype.
  3. The Object.prototype is on the top of the prototype chain.
  4. All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.  --quoted from w3schools
Simply, suppose that you are creating a function in javascript. That function also contain a prototype object.

//javascript prototypes
function Mammal(name,kingdom){
this.name = name;
this.kingdom = kingdom
this.info = function(){
return "name = " + this.name + ". kingdom = " + this.kingdom; 
}
}
//adding a static variable to the prototype object of the Mammal function
Mammal.prototype.sound = "GRRRRRRR"
//adding a static function to the prototype object of the Mammal functuon
Mammal.prototype.makeSound = function(){
return this.info() + ". And I make the sound " + this.sound;
}

var lion = new Mammal("lion", "Animalia");
console.log(lion.makeSound());
console.log(lion.info());

2. Printing out all the properties of a Javascript object


//let's print out all the properties of an object
for (var property in lion){
console.log(property + "\n");
}

3. Let's find out whether a certain property belongs to the object or it's specific prototype object


console.log(lion.hasOwnProperty("name")) // true, meaining this property belogns to the object itself not to it's prototype
console.log(lion.hasOwnProperty("kingdom")) // true
console.log(lion.hasOwnProperty("info")) //true
console.log(lion.hasOwnProperty("sound")) //false, meaing this property belongs to the prototype of that object
console.log(lion.hasOwnProperty("makeSound")) //false

4. let's create a program to search an array for a specific element using prototypes

Let's do a fun activity. In javascript there is an object called the Array object and we'll be adding a custom function to that array object to input an element and check whether it's present or not inside the array. To achieve this we'll be using a linear search of log(n) as an average.

//let's create a program to search an array for a specific element using prototypes
Array.prototype.findMe = function(number){
for(var i = 0; i < this.length ; i++){
if(this[i] == number){
return true;
}
}
return false;
}
var numberArray = [2,34,2,213,43,45];
console.log(numberArray.findMe(43)) 

2 comments:

  1. Good article with good examples ! :D

    ReplyDelete
    Replies
    1. Thanks! Stay tuned for the tutorial on Callbacks and some data visualizations with d3.js :)

      Delete