Hi guys,
We came back again to objects. It is big topic and to became comfortable in javascript , object deep knowledge is required . i cant skip it . So,without future dao , lets dig in.
Remember i told you that bracket notation is another way to access its value inside the objects . Bracket notation supports variable . so , if you write obj[var1] . it will substitute its variable . Dot notation fails here . we cant use obj.var1 .
For iterating all objects properties , we have special loop. known as for-in loop . lets take an example .
var obj1 = { first_name : "paritosh", last_name : "piplewar" }
for(var property in obj1){
console.log(property + " : " + obj1[property]);
}
In my previous guide,i taught you how to create constructor . In javascript , it is analogous with class , we define class in same way . Technically both are different, but this concept is confusing , so dont appy it here .
So, lets jump into prototype .
What is prototype ?
It is the property which spy all class methods and attributes. Prototype is often used to extend the class/constructor property by this syntax .
className.protpotype.newMethod = function() {}
You must be thinking what is the need to learn this concept. It is sometimes a situation where we cant change classdefinition, so we use prototype property . Let suppose , we want to add property in Array class. so
Array.prototype.firstElement = function() {
console.log(this[0]);
}
var arr2 = new Array();
arr2[0] = second;
console.log(arr2.firstElement());
Prototype is much more then that. We can inherit all class methods and attributes . Syntax is
childClass.prototype = new parentClass();
You can also declare private variable inside class. Its is so easy but just somewhat tricky. We use variable scope concept , variable which is defined inside block cant be accessed outside the block . if we try , we will get undefined . so, inside the class , we can use get / set methods for private attributes or/and methods . Like
var clas1 = function(college) {
var collegeName = college;
this.name = paritosh;
this.getCollegeName = function() {
return collegeName;
}
}
cls1 = new clas1(JEC);
console.log(cls1.getCollegeName());
This is for all now. Learn all this concept .