ObjectOriented JavaScript读书笔记下.docx

上传人:b****2 文档编号:11403558 上传时间:2023-05-31 格式:DOCX 页数:51 大小:383.63KB
下载 相关 举报
ObjectOriented JavaScript读书笔记下.docx_第1页
第1页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第2页
第2页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第3页
第3页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第4页
第4页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第5页
第5页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第6页
第6页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第7页
第7页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第8页
第8页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第9页
第9页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第10页
第10页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第11页
第11页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第12页
第12页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第13页
第13页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第14页
第14页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第15页
第15页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第16页
第16页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第17页
第17页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第18页
第18页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第19页
第19页 / 共51页
ObjectOriented JavaScript读书笔记下.docx_第20页
第20页 / 共51页
亲,该文档总共51页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

ObjectOriented JavaScript读书笔记下.docx

《ObjectOriented JavaScript读书笔记下.docx》由会员分享,可在线阅读,更多相关《ObjectOriented JavaScript读书笔记下.docx(51页珍藏版)》请在冰点文库上搜索。

ObjectOriented JavaScript读书笔记下.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 工程科技 > 能源化工

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2