JavaScript : Objects, Prototype, Inheritance, Window Object

In JavaScript almost everything is an object. Even primitive data types (except null and undefined) can be treated as objects. A JavaScript object is a complex variable, with properties and methods. We can create a Data type and then create objects using that data type. Lets just first create object without any data type.
Creating object using new keyword.


var person1 = new Object();
person1.firstname = "John";
person1.lastname = "Doe";
person1.age = 25;
var text = "";
for ( var x in person1) {
 text += person1[x];
}
alert(text);// will return JohnDoe25

The above code create person1 object and add three properties to it. This is an old way. A more efficient and easy way is by using object literal.


var person2 = {
 firstname : "Jane",
 lastname : "Doe",
 age : 25,

 getFullName : function(){
 return this.firstname+" "+this.lastname;
 }
};
alert(person2.getFullName());// will return Jane Doe

An object literal is a list of name:value pairs inside curly braces {}. Notice the declaration of method here.

Its now feasible to create a person object like this. Use of a Person data type will be better option. The first thing is to write a constructor function to create a person object from. This Person datatype is also an object.


function Person(fname, lname, age) {
 this.firstname = fname;
 this.lastname = lname;
 this.age = age;
 this.getFullName = function() {
 return this.firstname + " " + this.lastname;
 };
}
var person3 = new Person("John", "Doe", 26);
alert(person3.getFullName());//will return John Doe

 As a best practice we make first letter as capital for ant Data type, its not compulsary but will be easier distinguishable from the other functions.

Inheritance in javascript is different from other oo languages like java,c++. We have several different patterns for it in javascript but the most important is the prototypal inheritance. Earlier we created a Person data type which had 3 properties and a method. So for every object created using this, these 4 members are created. Members is just properties or methods. For properties, it makes sence as each object will have some unique values for it, but the method doesnt need to be recreated eachtime. A method is going to do the same thing in every object.  We can put this getFullName method on the prototype of the person object or the person data type. Prototype is shared among all objects of a particular datatype. Prototype is actually a property of a function. Putting getFullName in prototype:


function Person(fname, lname, age) {
 this.firstname = fname;
 this.lastname = lname;
 this.age = age;
}
Person.prototype.getFullName = function() {
 return this.firstname + " " + this.lastname;
};
var person1 = new Person("John", "Doe", 26);
alert(person1.getFullName());

Whenever getFullName is called, javascript will first search the getFullName in the person1 object and will not find it, then it will search the prototye of Person, and will execute the method. The following code will produce different result at the last alert:


function Person(fname, lname, age) {
 this.firstname = fname;
 this.lastname = lname;
 this.age = age;
}
Person.prototype.getFullName = function() {
 return this.firstname + " " + this.lastname;
};
var person1 = new Person("John", "Doe", 26);
alert(person1.getFullName());//output - John Doe

person1.getFullName=function() {
 return this.firstname + " " + this.lastname+" from person1";
};

alert(person1.getFullName());//output - John Doe from person1

In the second case javascript first looked into object itself for the method and found one, so the method in the prototype of Person datatype was never called.

Lets create an Employee datatype using inheritance.


function Person(fname, lname, age) {
 this.firstname = fname;
 this.lastname = lname;
 this.age = age;
}
Person.prototype.getFullName = function() {
 return this.firstname + " " + this.lastname;
};

function Employee(fname, lname, age, position) {
 Person.call(this, fname, lname, age);
 this.position = position;
}
Employee.prototype = new Person();
var employee1 = new Employee("Jane", "Doe", 26, "programmer");
alert(employee1.getFullName());

Above we are creating a new function Employee. We want to reuse the Person datatype for firstname, lastname, age. We can do that by using Person object. Every function object has a method ‘call’ whose argumets are (object,objectArgumetns..). The first value in the argumets is the object that we want person to execute as, so we are calling Person as if it was an Employee (‘this’ in Person refers to an Employee object ). The second argumets are the values to be passed in Person.
To get the method in Employee we create a new Person bject and assign it to Employee prototype.

Suppose we want to customize our getFullName in Employee to return position as well. That can be done as follows.


//above code same as previous
Employee.prototype = new Person();
Employee.prototype.getFullName=function() {
 var fullName=Person.prototype.getFullName.call(this);
 return fullName +", " + this.position;
};
var employee1 = new Employee("Jane", "Doe", 26, "programmer");
alert(employee1.getFullName());

Now when getFullName of Employee is called, it will first call the Person getFullName as an Employee object, then will concenate the position.

Window Object

In the browser we have a object called ‘window’ and this is our global scope. Whenever we create a global variable or function, its actually been added to this window object.  For exampe, if we declare
var x=10;
Now to access this we use just ‘x’, we can use ‘window.x’ but here its no use. One of the senarios where you might need to use the ‘window’ object is when the local varialbe is of same name as that of global. To access the global variable we have to use ‘window’ now.


var x=10;
function calculate(x,y){

var sum=x+y;//here local x will be used
var anotherSum=window.x+y;// here global x(10) will be used

}

Similarly alert and window.alert are kind of same, alert is the method of window object. Window object can also be used to modify the actual physical window in browser. Lets see following code:


var newWindow=open("http://www.google.com", null, "height=400, width=500");

Running this will open a new window with google. As per javascript security, two windows with different origin cannot communicate with each other. So, even though we have the object in variable , we cannot do anything on it. Lets change above code:


var x="From parent";
var newWindow=open("New_window1.html", null, "height=400, width=500");

Create a new html – New_window.html in the same pages folder :


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
alert(opener.x);
</script>
</head>
<body>
Hi There!!
</body>
</html>

opener is the object of the window that opened this new window. Here we will get an alert which access the variable in the parent window. Lets write something from parent to child. Creating new file – New_window2.html:


<!DOCTYPE html>
<html>
<head>
<title>New Window</title>
<script type="text/javascript">
var childWindow=open("", null,"height=400, width=500");
childWindow.document.write("Hi!!!<br/>");
childWindow.document.write("There!<br/>");
childWindow.document.close();
</script>
</head>
<body>

</body>
</html>

This will write these 2 lines in the child window.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: