Javascript - Objects PDF
Javascript - Objects PDF
Note:manyofthecontentsofthispagearetakenfromw3schoolwebsite.
JavaScriptObjects
ObjectOrientedProgramming
JavaScriptisanObjectOrientedProgramming(OOP)language.AnOOPlanguageallowsyoutodefine
yourownobjectsandmakeyourownvariabletypes.
However,creatingyourownobjectswillbeexplainedlater,intheAdvancedJavaScriptsection.Wewill
startbylookingatthebuiltinJavaScriptobjects,andhowtheyareused.Thenextpageswillexplain
eachbuiltinJavaScriptobjectindetail.
Notethatanobjectisjustaspecialkindofdata.Anobjecthaspropertiesandmethods.
Properties
Propertiesarethevaluesassociatedwithanobject.
InthefollowingexampleweareusingthelengthpropertyoftheStringobjecttoreturnthenumberof
charactersinastring:
<scripttype="text/javascript">
vartxt="HelloWorld!"
document.write(txt.length)
</script>
Theoutputofthecodeabovewillbe:
12
Methods
Methodsaretheactionsthatcanbeperformedonobjects.
InthefollowingexampleweareusingthetoUpperCase()methodoftheStringobjecttodisplayatextin
uppercaseletters:
<scripttype="text/javascript">
varstr="Helloworld!"
document.write(str.toUpperCase())
</script>
Theoutputofthecodeabovewillbe:
HELLOWORLD!
CreatingNewObjects
JavaScriptObjects
EarlierwehaveseenthatJavaScripthasseveralbuiltinobjects,likeString,Date,Array,andmore.In
additiontothesebuiltinobjects,youcanalsocreateyourown.
Anobjectisjustaspecialkindofdata,withacollectionofpropertiesandmethods.
Let'sillustratewithanexample:Apersonisanobject.Propertiesarethevaluesassociatedwiththe
object.Thepersons'propertiesincludename,height,weight,age,skintone,eyecolor,etc.All
personshavetheseproperties,butthevaluesofthosepropertieswilldifferfrompersontoperson.
Objectsalsohavemethods.Methodsaretheactionsthatcanbeperformedonobjects.Thepersons'
methodscouldbeeat(),sleep(),work(),play(),etc.
Properties
Thesyntaxforaccessingapropertyofanobjectis:
objName.propName
Youcanaddpropertiestoanobjectbysimplygivingitavalue.AssumethatthepersonObjalreadyexists
youcangiveitpropertiesnamedfirstname,lastname,age,andeyecolorasfollows:
personObj.firstname="John"
personObj.lastname="Doe"
personObj.age=30
personObj.eyecolor="blue"
document.write(personObj.firstname)
Thecodeabovewillgeneratethefollowingoutput:
John
Methods
Anobjectcanalsocontainmethods.
Youcancallamethodwiththefollowingsyntax:
objName.methodName()
Note:Parametersrequiredforthemethodcanbepassedbetweentheparentheses.
Tocallamethodcalledsleep()forthepersonObj:
personObj.sleep()
CreatingYourOwnObjects
Therearedifferentwaystocreateanewobject:
1.Createadirectinstanceofanobject
Thefollowingcodecreatesaninstanceofanobjectandaddsfourpropertiestoit:
personObj=newObject()
personObj.firstname="John"
personObj.lastname="Doe"
personObj.age=50
personObj.eyecolor="blue"
AddingamethodtothepersonObjisalsosimple.Thefollowingcodeaddsamethodcalledeat()tothe
personObj:
personObj.eat=eat
2.Createatemplateofanobject
Thetemplatedefinesthestructureofanobject:
functionperson(firstname,lastname,age,eyecolor)
{
this.firstname=firstname
this.lastname=lastname
this.age=age
this.eyecolor=eyecolor
}
Noticethatthetemplateisjustafunction.Insidethefunctionyouneedtoassignthingsto
this.propertyName.Thereasonforallthe"this"stuffisthatyou'regoingtohavemorethanone
personatatime(whichpersonyou'redealingwithmustbeclear).That'swhat"this"is:theinstanceof
theobjectathand.
Onceyouhavethetemplate,youcancreatenewinstancesoftheobject,likethis:
myFather=newperson("John","Doe",50,"blue")
myMother=newperson("Sally","Rally",48,"green")
Youcanalsoaddsomemethodstothepersonobject.Thisisalsodoneinsidethetemplate:
functionperson(firstname,lastname,age,eyecolor)
{
this.firstname=firstname
this.lastname=lastname
this.age=age
this.eyecolor=eyecolor
this.newlastname=newlastname
}
Notethatmethodsarejustfunctionsattachedtoobjects.Thenwewillhavetowritethenewlastname()
function:
functionnewlastname(new_lastname)
{
this.lastname=new_lastname
}
Thenewlastname()functiondefinestheperson'snewlastnameandassignsthattotheperson.
JavaScriptknowswhichpersonyou'retalkingaboutbyusing"this.".So,nowyoucanwrite:
myMother.newlastname("Doe").
2007MehmudAbliz