JavaScript-1:Objectsand
Prototypes
CPEN400A– Lecture2
(Basedonthebook“JavaScript:TheGood
Parts”byDougCrockford,O’ReillyPress
Outline
• JavaScript:HistoryandPhilosophy
• ObjectcreationinJavaScript
• Prototypesandinheritance
• Type-checkingandreflection
JavaScript:History
• Inventedin10daysbyBrendanEich atNetscape
inMay1995aspartoftheNavigator2.0browser
– BasedonSelf,butdresseduptolooklikeJava
– Standardizedbycommitteein2000asECMAScript
JavaScript(JS)hadto“looklikeJava”
onlylessso,beJava’sdumbkidbrother
orboy-hostagesidekick.Plus,Ihadtobe
doneintendaysorsomethingworse
thanJSwouldhavehappened
– BrendanEich (InventorofJavaScript)
JavaScript:Philosophy- 1
• Everythingisanobject
– Includesfunctions,non-primitivetypesetc.
– Eventheclassofanobjectisanobject!
• Nothinghasatype
– Oritstypeiswhatyouwantittobe(ducktyping)
– Nocompile-timechecking(unlessinstrictmode)
– Runtimetypeerrorscanoccur
JavaScript:Philosophy- 2
• Programmersmakemistakesanyways
– Ifanexceptionisthrown,donotterminate
program(artifactofbrowsers,ratherthanJS)
• Codeisnodifferentfromdata
– Sowecanuse‘eval’toconvertdatatocode
• Function’scanbecalledwithfewerormore
argumentsthanneeded(variadic functions)
JavaScript:“Good”or“Evil”?
Vs.
Eval Calls(fromRichardsetal.[PLDI-2010])
E
v
a
l
s
100000
10000
1000
100
10
Realwebapplicationsdonotsticktothe“good”parts
1
0.1
6
Philosophyofourcourse
• We’lltryandusethegoodsubsetofJavaScriptas
faraspossibleasinDougCrockford’s book
• However,we’llalsolearnaboutthe“evil”
featuresofJSsothatwecanrecognizethem
– Sometimesthereisagoodreasonforusinganevil
feature(e.g.,eval isanelegantwaytoparseJSON)
– Sometimesyouhavetodealwithlegacycodeorcode
writtenbyotherswhomayusethesefeatures
Outline
• JavaScript:HistoryandPhilosophy
• ObjectcreationinJavaScript
• Prototypesandinheritance
• Type-checkingandreflection
WhatisanObjectinJS?
• Containerofproperties,whereeachproperty
hasanameandavalue,andismutable
– Propertynamescanbeanystring,includingthe
emptystring
– Propertyvaluescanbeanythingexceptundefined
• Whatarenotobjects?
– Primitivetypessuchasnumbers,booleans,strings
– nullandundefined – thesearespecialtypes
Whataboutclasses?
• TherearenoclassesinJavaScript,aswe
understandtheminlanguagessuchasJava
• “What?Howcanwehaveobjectswithout
classes?”
– Objectsusewhatareknownasprototypes
– Anobjectcaninheritthepropertiesofanother
objectusingprototypelinkage(morelater)
ExampleofObjectCreation
• var empty_object ={};
• var name={
firstName:“Karthik”,
lastName:“Pattabiraman”;
};
NOTE:Youdon’tneedaquotearoundfirstName
andlastName asthey’revalidJavaScriptidentifiers
RetrievinganObject’sproperty
name[“firstName”]ORname.firstName
name[“lastName”]ORname.lastName
Whatifyouwritename[“middleName”]?
Returnsundefined.Lateruseofthisvaluewill
resultinan“TypeError”exceptionbeingthrown
UpdateofanObject’sProperty
name[“firstName”]=“DifferentfirstName”;
name.lastName =“DifferentlastName”;
Whathappensifthepropertyisnotpresent?
- It’llgetaddedtotheobjectwiththevalue
Inshort,objectsbehavelikehashtablesinJS
ObjectsarepassedbyREFERENCE!
• InJavaScript,objectsarepassedbyREFRENCE
– Nocopiesareevermadeunlessexplicitlyasked
– Changesmadeinoneinstanceareinstantlyvisible
inallinstancesasitisbyreference
Example:
var a={field:value};
var b=a;
b.field =new-value;
ObjectCreationusingNew
‘new’operatortocreateanobjectofinstance
‘Object’,whichisaglobal,uniqueJavaScriptobject
var Person=function(firstName,lastName,gender)
{
this.firstName=firstName;
this.lastName =lastName;
this.gender =gender;
}
var p=newPerson(“John”,“Smith”,“Male”);
Howtousenew?
• Definetheobjecttypebywritinga
“Constructorfunction”
– Byconvention,useacapitalletterasfirstletter
– Use“this”withinfunctiontoinitializeproperties
(wewillseewhythisisnecessarylater)
• Callconstructorfunctionwiththenew
operatorandpassitthevaluestoinitialize
– Forgettingthe‘new’canhaveunexpectedeffects
Outline
• JavaScript:HistoryandPhilosophy
• ObjectcreationinJavaScript
• Prototypesandinheritance
• Type-checkingandreflection
ObjectPrototype
• Everyobjecthasafieldcalled‘Prototype’
– Prototypeisapointertotheobjecttheobjectis
createdfrom(i.e.,theclassobject)
– Changingtheprototypeobjectinstantlychanges
allinstancesoftheobject
• Thedefaultprototypevalueis“Object”
– CanbechangedwhenusingneworObject.create
ObjectPrototype:Example
• Inthepreviousexample,whatisthe
prototypevalueofa“Person”object?
var p=newPerson(“John”,“Smith”,“Male”);
console.log(Object.getPrototypeOf(p));
Whatwillhappenifwedothefollowinginstead
console.log(Object.getPrototypeOf(Person));
PrototypeField
• Prototypesofobjectscreatedthrough{}is
– Object.prototype
• PrototypeofobjectscreatedusingnewObject
– Object.prototype
• Prototypeofobjectscreatedusingnewand
constructorsfunctions(e.g.,Person)
– Prototypefieldoftheconstructorfunction(ifobject)
– Object.prototype (otherwise)
What‘new’reallydoes
• Initializesanewnativeobject
• Setstheobject’sprototypefieldtothe
constructorfunction’sprototypefield
– Ifit’snotanObject,setsittoObject.prototype
• Callstheconstructorfunction,withobjectasthis
– Anyfieldsinitializedbythefunctionareaddedtothis
– Returnstheobjectcreatedifandonlyifthe
constructorfunctionreturnsaprimitivetype
PrototypeModification
• Anobject’sprototypeobjectisjustanother
object(typically).Soitcanbemodifiedtoo.
• Wecanaddpropertiestoprototypeobjects–
thepropertybecomesinstantlyvisibleinall
instancesofthatprototype(eveniftheywere
createdbeforethepropertywasadded)
– Reflectsinalldescendantobjectsaswell(later)
PrototypeModification:Example
var p1=newPerson(“John”,“Smith”,“Male”);
Person.prototype.print =function(){
console.log(“Person:“+this.firstName
+this.lastName +this.gender +“\n”);
}
var p2=newPerson(“Linda”,“James”,“Female”);
p1.print();
p2.print();
DelegationwithPrototypes
• WhenyoulookupanObject’sproperty,and
thepropertyisnotdefinedintheObject,
– ItchecksiftheObject’sprototypeisavalidobject
– Ifso,itdoesthelookupontheprototypeobject
– Ifitfindstheproperty,itreturnsit
– Otherwise,itrecursivelyrepeatstheabove
processtillitencountersObject.prototype
– Ifitdoesn’tfindthepropertyevenafterallthis,it
returnsUndefined
PrototypeInheritance
• DuetoDelegation,Prototypescanbeusedfor
(simulating)inheritanceinJavaScript
– Settheprototypefieldofthechildobjecttothat
oftheparentobject
– Anyaccesstochildobject’spropertieswillfirst
checkthechildobject(soitcanover-ridethem)
– Ifitcan’tfindthepropertyinthechildobject,it
looksuptheparentobjectspecifiedinprototype
– Thisprocesscarriesonrecursivelytillthetopof
theprototypechainisreached(object.prototype)
PrototypeInheritance:Example
var Employee=function(firstName,lastName,
Gender,title){
Person.call(this,firstName,lastName,Gender);
this.title =title;
}
Whyshould you
createanew
Employee.prototype =new Person();
person object?
Employee.prototype.constructor =Employee;
var emp =newEmployee(“ABC”,“XYZ”,
“Male”,“Manager”);
Object.create(proto)
• Createsanewobjectwiththespecified
prototypeobjectandproperties
• DefinedasapropertyoftheObject– so
availabletoallobjectsinJavaScript
• protoparametermustbenulloranobject
– ThrowsTypeError otherwise
Object.create Argument
• Canspecifyinitializationparametersdirectlyin
Object.create asan(optional)2nd argument
var e=Object.create(Person,
{Title:{value:“Manager”}})
Wecanspecifyotherelementssuchas
enumerable, configurable etc.(morelater)
PrototypeInheritancewith
Object.create:Example
var Person={
firstName:“John”;
lastName:“Smith”;
gender:“Male”;
print:function(){
console.log(“Person:“+this.firstName
+this.lastName +this.gender;
}
};
var e=Object.create(Person);
e.title =“Manager”;
DesignTips
• Object.create ismuchcleanerthanusingnewand
.prototype(noneedforartificialobjects)
• Withnew,youneedtoremembertousethis and
alsoNOTreturnanobjectintheconstructor
– Otherwise,badthingscanhappen
• Object.create allowsyoutocreateobjects
withoutrunningtheirconstructorfunctions
– Needtorunyourconstructormanuallyifyouwant
ClassActivity
• Constructaclasshierarchywiththefollowing
propertiesusingbothpseudo-classinheritance
(throughconstructors)andprototypalinheritance
(thro’Object.create).Addanareamethodanda
toString prototypefunctiontoalltheobjects.
Point{x,y}
Circle{r}
Ellipse{r,r2}
Outline
• JavaScript:HistoryandPhilosophy
• ObjectcreationinJavaScript
• Prototypesandinheritance
• Type-checkingandReflection
ReflectionandType-Checking
• InJS,youcanqueryanobjectforitstype,
prototype,andpropertiesatruntime
– TogetthePrototype:getPrototypeOf()
– Togetthetypeof:typeof
– Tocheckifit’sofcertaininstance:instanceof
– Tocheckifithasacertainproperty:in
– Tocheckifithasaproperty,andthepropertywas
notinheritedthroughtheprototypechain:
hasOwnProperty()
typeof
• Canbeusedforbothprimitivetypesandobjects
typeof(Person.firstName )à String
typeof(Person.lastName )à String
typeof(Person.age )à Number
typeof(Person.constructor)à function(prototype)
typeof(Person.toString)à function(fromObject)
typeof(Person.middleName)à undefined
instanceof
• Checksifanobjecthasinitsprototypechainthe
prototypepropertyoftheconstructor
object instanceof constructorà Boolean
var p=newPerson(…);
var e=newEmployee(…);
pinstanceof Person;
à True
pinstanceof Employee;
à False
einstanceof Person;
à True
einstanceof Employee;
à True
pinstanceof Object;
à True
einstanceof Object;
à True
getPrototypeOf
• Getsanobject’sprototype(Fromthe
prototypefield)– Object.getPrototypeOf(Obj)
– Equivalentof‘super’inlanguageslikeJava
var proto={};
var obj =Object.create(proto);
Object.getPrototypeOf(obj);à proto
Object.getPrototypeOf(proto);à Object
inoperator
• Testsifanobjectohaspropertyp
– Checksbothobjectanditsprototypechain
var p=newPerson(…);
var e=newEmployee(…);
“firstName”inp;à True
“lastName”ine;à True
“Title”inp;à False
hasOwnProperty
• Onlycheckstheobject’spropertiesitself
– Doesnotfollowtheprototypechain
– Usefultoknowifanobjecthasoverriddena
propertyorintroducedanewone
var p=newEmployee(…);
p.hasOwnProperty(“Title”)à True
p.hasOwnProperty(“FirstName”)à False
IteratingoveranObject’sfields
• Gooverthefieldsofanobjectandperformsome
action(s)onthem(e.g.,printthem)
– CanusehasOwnProperty asafilterifneeded
var name;
for(nameinobj){
if(typeof(obj[name])!=“function”){
document.writeln(name+“:“+obj[name]);
}
}
RemovinganObject’sProperty
• Toremoveapropertyfromanobjectifithas
one(notremovedfromitsprototype),use:
deleteobject.property-name
Propertiesinheritedfromtheprototypecannotbe
deletedunlesstheobjecthadoverriden them.
var e=newEmployee(…);
deletee.Title;//Titleisremovedfrome
ObjectPropertyTypes
• Propertiesofanobjectcanbeconfiguredto
havethefollowingattributes(ornot):
– Enumerable:Showupduringenumeration(for..in)
– Configurable:Canberemovedusingdelete,and
theattributescanbechangedaftercreation
– Writeable:Canbemodifiedaftercreation
• Bydefault,allpropertiesofanobjectare
enumerable,configurableandwriteable
SpecifyingObjectPropertytypes
• CanbedoneduringObjectcreationwithObject.create
var e=Object.create(Person,
{Title:{value:“Manager”,
enumerable:true;
configurable:true;
writeable:false;
});
CanbedoneaftercreationusingObject.defineProperty
Object.defineProperty(Employee,“Title”,{value:“Manager”,
enumerable:true;configurable:true;writable:false});
DesignGuidelines
• Usefor…inloopstoiterateoverobject’s
propertiestomakethecodeextensible
– Avoidhardcodingpropertynamesifpossible
– Useinstanceof ratherthangetPrototypeOf
• Trytofixtheattributesofapropertyatobject
creationtime.Withveryfewexceptions,there
isnoneedtochangeaproperty’sattribute.
ClassActivity
• Writeamethodtoiterateovertheproperties
ofagivenobject,andidentifythose
propertiesthatitinheritedfromitsprototype
ANDoverrodeitwithitsownvalues
– Removeallsuchpropertiesfromtheobject
Outline
• JavaScript:HistoryandPhilosophy
• ObjectcreationinJavaScript
• Prototypesandinheritance
• Type-checkingandReflection
© Copyright 2026 Paperzz