Published on: 12/18/13 5:04 PM
Category:Javascript Tags: javascriptHello All !
Today we will see how to start studying object oriented javascript
This will be just how to begin use javascript with great Object oriented approach
1) First How to create objects in javascript ?
there are two ways to create an object 1) Constructor Function
2) Literal function
We can declare this function as
1) Constructor function
function myObject(){ }
2) Literal Notation
var myObject={ };
Literal is preferable option for name spacing so javascript code doesn’t interface with other language scripting code on the same page or an application
Now we will see how to define method and properties in both of this object types
1) Constructor version
[code language=”javascript”]
function myObject(){
this.iAm = ‘an Object’ ;
this.whatIAm = function(){
alert(‘I am’ + this.iAm);
}
}
[/code]
2) Literal version
[code language=”javascript”]
var myObject={
iAm:’an object’,
whatIam: function(){
alert(‘I am’+this.iAm);
}
}
[/code]
“Properties are variable created inside the object and methods are functions inside objects”
– To use properties, first you type the object it belongs to then for example for our case it will be
[code language=”javascript”]
myObject.whatIam
[/code]
this will return ‘an object’
-To use method
this is same just put parenthesis after it ; otherwise you will just return the referance to function and not what the actual function return so it will like
[code laguage=”javascript”]
myObject.whatIam()
[/code]
it will return ‘an object’
Now we will see what are the difference in the both of this
1) Constructor object has properties and method defined with keywords ‘this’ in front of it, whereas literal version doesn’t
2) In constructor object the properties/ methods have there ‘values’ defined after ‘=’ where in literal, they are define after “:”
3) Constructor function can have semicolon (‘;’) at end of each property / method whereas in literal if we have more than one method / property they separated by comma (‘,’)
4) Object declaration
for literal we can declare as
[code language=”javascript”]
myObject.whatIam();
[/code]
for constructor
[code language=”javascript”]
var myNewObject= new myObject();
myNewObject.whatIAm();
[/code]
Using a construction function
when we instantiate, then function will perform some basic operation
for example
[code language=”javascript”]
function myObject(){
this.IAm =’an object’ ;
this.whatIAm = function (){
alert("I am" +this.IAm);
};
};
[/code]
we also can pass the argument to function
for example
[code language=”javascript”]
function myObject(what) {
this.IAm = what ;
this.whatIAm= function (language) {
alert("I am " + this.IAm + "at" + language +"language" );
};
};
[/code]
To call above function, we can have
[code language=”javascript”]
var myNewObject = new myObject(‘an object’);
myNewObject.whatIam(‘javascript’);
[/code]
then this will alert
“I am an object at javascript language”
0 thoughts on "Object Oriented Javascript"