ObjectOriented JavaScript读书笔记下.docx
《ObjectOriented JavaScript读书笔记下.docx》由会员分享,可在线阅读,更多相关《ObjectOriented JavaScript读书笔记下.docx(51页珍藏版)》请在冰点文库上搜索。
![ObjectOriented JavaScript读书笔记下.docx](https://file1.bingdoc.com/fileroot1/2023-5/31/bb7e02b5-07fc-4b76-9e92-6419004856ba/bb7e02b5-07fc-4b76-9e92-6419004856ba1.gif)
ObjectOrientedJavaScript读书笔记下
Chapter5Prototype
1.Theprototypeproperty:
availabletoyouassoonasyoudefinethefunction.
typeoffoo.prototype;
>"object"//Itsinitialvalueisan"empty"object.
2.Addingmethodsandpropertiesusingtheprototype
functionGadget(name,color){
this.name=name;
this.color=color;
this.whatAreYou=function(){
return'Iama'+this.color+''+this.name;
};
}//Anexemplaryobject
Gadget.prototype.rating=3;//Useprototypetoaddmethod
Gadget.prototype.getInfo=function(){
return'Rating:
'+this.rating+',price:
'+this.price;
};
//Notedthatoncetheprototypefunctionisdeclared,allobjectscanaccesstoit
//It’salivechange
3.Ownpropertiesversusprototypeproperties
a)WhatdoestheJavaScriptenginedowhenwewanttoaccesstooneproperty?
i.TheJavaScriptenginelooksthroughallofthepropertiesoftheobject.
ii.Thescriptengineidentifiestheprototypeoftheconstructorfunctionusedtocreatethisobject
newtoy.constructor===Gadget;
>true
newtoy.constructor.prototype.rating;
>3
b)Object()isthecommonparentofallobjects,sotoString()canbeinheritedfromit.
4.Overwritingaprototype'spropertywithanownproperty
a)theownpropertytakesprecedenceovertheprototype's
Example:
functionGadget(name){
this.name=name;
}
Gadget.prototype.name='mirror';
vartoy=newGadget('camera');//Creatinganewobjectandaccessingitsname
toy.name;//propertygivesyoutheobject'sownnameproperty
>"camera"
toy.hasOwnProperty('name');//hasOwnProperty()tellswherethepropertywasdefined.
>true
deletetoy.name;
toy.name;
>"mirror"//Nowtheprototypevariableshinesthrough
Object.hasOwnProperty('toString');
>false
Object.prototype.hasOwnProperty('toString');
True//toString()isdefinedinObject.prototype
b)instance.constructor.prototype=object.prototype
rememberthatonlyconstructorcanbeusedtochangeprototype
5.Enumeratingproperties
a)forisbettersuitedforarraysandfor-inisforobjects
Example:
varparams={
productid:
666,
section:
'products'
};
query=[];
for(variinparams){//iteratingtheobjectusingthekey
query.push(i+'='+params[i]);//remembertousevar
}
b)Note:
i.Onlyenumerablepropertiesshowupinafor-inloop.Forexample,thelength(forarrays)andconstructorpropertiesdon'tshowup.
ii.Enumerableprototypesthatcomethroughtheprototypechainalsoshowup.
iii.propertyIsEnumerable()returnsfalseforalloftheprototype'sproperties,eventhosethatareenumerableandshowupinthefor-inloop.
newtoy.propertyIsEnumerable('price');
>false
newtoy.constructor.prototype.propertyIsEnumerable('price');
>true//Remembertousetheobject/constructortoaccesstheprototypeproperty
6.isPrototypeOf()
functionHuman(name){
this.name=name;
}
Human.prototype=monkey;//monkeymustbeanobject,notanconstructor
vargeorge=newHuman('George');
monkey.isPrototypeOf(george);//Thismethodtellsyouwhetherthatspecificobject
>true//isusedasaprototypeofanotherobject.
Object.getPrototypeOf(george)//youcan'tinallbrowsers,butyoucaninmostofthem
>monkey;
7.Thesecret__proto__link
a)ThesecretlinkisexposedinmostmodernJavaScriptenvironmentsasthe__proto__property.
varmonkey={
feeds:
'bananas',
breathes:
'air'
};
functionHuman(){}
Human.prototype=monkey;
developer.__proto__===monkey;//don’tuseitinyourrealscriptsbecause
//itdoesnotexistinallbrowsers
b)__proto__isnotthesameasprototype,since__proto__isapropertyoftheinstances(objects),whereasprototypeisapropertyoftheconstructorfunctionsusedtocreatethoseobjects.
8.Augmentingbuilt-inobjects:
addpersonalfunctionalities
a)Example:
String.prototype.reverse=function(){
returnArray.prototype.reverse.apply(this.split('')).join('');
};//Addareversemethodtothestringobject
b)OnceyouknowJavaScript,you'reexpectingittoworkthesameway,nomatterwhichthird-partylibraryorwidgetyou'reusing.Modifyingcoreobjectscouldconfusetheusersandmaintainersofyourcodeandcreateunexpectederrors.
c)Themostcommonandacceptableusecaseforaugmentingbuilt-inprototypesistoaddsupportfornewfeatures(onesthatarealreadystandardizedbytheECMAScriptcommitteeandimplementedinnewbrowsers)tooldbrowsers.
d)if(typeofString.prototype.trim!
=='function'){
String.prototype.trim=function(){//Youshouldfirstcheckifthefunctionhas
returnthis.replace(/^\s+|\s+$/g,'');//beendefined
};
}
9.Prototypegotchas
a)Theprototypechainisliveexceptwhenyoucompletelyreplacetheprototypeobject
b)prototype.constructorisnotreliable
Dog.prototype={//thisshouldbeavoidedinpracticaluse.
paws:
4,//Itturnsoutthattheoldobjectsdonotgetaccesstothe
hair:
true//newprototype'sproperties
};
lucy.constructor;//constructorpropertyofthenew
functionObject(){[nativecode]}//objectnolongerreportscorrectly
c)bestpractice:
Whenyouoverwritetheprototype,remembertoresettheconstructorproperty.
Dog.prototype.constructor=Dog;//rememberit’sobject.prototype.constructor
d)varshape={//Thismustbeanobject
property:
"shape",
gettype:
function(){returnthis.property;}
}
functionTriangle(a,b,c){
this.property="triangle",
this.a=a,this.b=b,this.c=c
}
Triangle.prototype=shape;//resettheprototype
Triangle.prototype.constructor=shape;//resettheconstructoroftheprototype
Triangle.prototype.getPerimeter=function(){returnthis.a+this.b+this.c}
Chapter6Inheritance
1.Prototypechaining:
defaultwayofimplementinginheritance
a)Thisallowsmethodsandpropertiesoftheprototypeobjecttobeusedasiftheybelongedtothenewly-createdobject.
b)Prototypealsohaslinkstotheirprototypes,prototypechain,endingwithObject.prototype.
c)Anobjectcanaccessanypropertyfoundsomewheredowntheinheritancechain.
2.Prototypechainingexample
a)functionShape(){
this.name='Shape';
this.toString=function(){
returnthis.name;
};
}
functionTwoDShape(){
this.name='2Dshape';
}//rememberthatJavaScriptworkswithobjects,notclasses
TwoDShape.prototype=newShape();//Thisisthekeyofinheritance
TwoDShape.prototype.constructor=TwoDShape;
//Alsoresettheconstructorpropertytoavoidsideeffect
3.Movingsharedpropertiestotheprototype:
ownpropertiesarenotefficient
a)functionShape(){//Thisisnotefficient
this.name='Shape';//nameiscopiedforeveryobject.
}
functionShape(){}
Shape.prototype.name='Shape';
//onlyuseitforpropertiesthatdon'tchangefromoneinstancetoanother.
TwoDShape.prototype=newShape();//inheritfromShape
TwoDShape.prototype.constructor=TwoDShape;//augmentprototype
TwoDShape.prototype.name='2Dshape';
//Inheritancefirstbeforeaugmentingtheprototype.Otherwiseallaugmentedmemberswillbewipedout.
TwoDShape.prototype.isPrototypeOf(my);
>true//TwoDShape.prototypeisanobject
4.Inheritingtheprototypeonly:
moreefficientthatinheritingnewShape()
a)newShape()onlygivesyouownshapepropertiesthatarenotmeanttobereused(otherwisetheywouldbeintheprototype).Yougainalittlemoreefficiencyby:
•Notcreatinganewobjectforthesakeofinheritancealone
•Havinglesslookupsduringruntime
b)originalone:
TwoDShape.prototype=newShape();
TwoDShape.prototype=Shape.prototype;//Thisismoreefficient,
//sideeffect:
becausealltheprototypesofthechildrenandparentspointtothesameobject,whenachildmodifiestheprototype,theparentsgetthechanges.
5.Atemporaryconstructor–newF():
useanintermediarytobreakthechain.
a)varF=function(){};//Anemptyfunction
F.prototype=Shape.prototype;
TwoDShape.prototype=newF();
TwoDShape.prototype.constructor=TwoDShape;
b)Usethistosupportstheideathatonlypropertiesandmethodsaddedtotheprototypeshouldbeinherited,andownpropertiesshouldnotwhilethechainisbroken.
6.Uber–accesstotheparentfromachildobject.LiketheJavasuperkeyword
functionShape(){}//Emptyobject
Shape.prototype.name='Shape';
Shape.prototype.toString=function(){
Varconst=this.constructor;//constistheclassnow.
returnconst.uber?
this.const.uber.toString()+','+this.name:
this.name;
};
TwoDShape.uber=Shape.prototype;//Use[class-level]propertytoinheritmethod
my.toString();//TheresultisthatwhenyoucalltoString(),alltoString()
>"Shape,2Dshape,Triangle"//methodsuptheprototypechainarecalled
7.Isolatingtheinheritancepartintoafunction
functionextend(Child,Parent){
varF=function(){};
F.prototype=Parent.prototype;
Child.prototype=newF();
Child.prototype.constructor=Child;
Child.uber=Parent.prototype;
}
functionTwoDShape(){}//define->inherit->augment
extend(TwoDShape,Shape);
TwoDShape.prototype.name='2Dshape';
8.Copyingproperties
a)Adifferentapproach:
copiesallofthepropertiesfromtheparent'sprototypetothechild'sprototype.
functionextend2(Child,Parent){
varp=Parent.prototype;
varc=Child.prototype;
for(variinp){//Thismethodisalittleinefficientcomparedtothechild
c[i]=p[i];//previousmethodbecausepropertiesoftheprototypeare
}//beingduplicated
c.uber=p;//hereuberisdefinedinprototype
}
b)Althoughit’snotthatefficient,butnotsobadbecauseonlytheprimitivedatatypesareduplicated.Additionally,thisisbeneficialduringtheprototypechainlookupsastherearefewerchainlinkstofollowbeforefindin