oop - Is Module pattern in javascript worth using? -
afaik understand module pattern in javascript, used create namespace variables , functions become private namespace save them inadvertent manipulation. e.g. consider following code:
var istouchdevice = 'ontouchstart' in document.documentelement; //some code... if(istouchdevice == 1) { alert("you using touchscreen device"); }
in above code if mistake had skipped 1 equal sign in if condition if(istouchdevice = 1)
pollute whole code , further conditions check value of istouchdevice
give false result. afai module pattern supposed solve these kind of issues. e.g. can make istouchdevice
readable read-only thing. think modular code be:
var useragent = function() { var touchdevice = 'ontouchstart' in document.documentelement; function istouchdevice() { return touchdevice; } return { iftouchdevice: istouchdevice }; }();
now if want check whether device touch screen do:
if(useragent.iftouchdevice())
or if(useragent.iftouchdevice() == 1)
now inadverdantly change useragent.iftouchdevice()
such if(useragent.iftouchdevice = 1)
, touchdevice
remain immutable , give correct value. far good. question is,
- we using
if(useragent.iftouchdevice() == 1)
everywhere check touch screen device , think module pattern save us. ifuseragent.iftouchdevice
has been assigned incorrect valueif
conditions checking touch device still go wrong. have madetouchdevice
immutable stilluseragent.iftouchdevice
not immutable , acts global variable can polluted. advantage of module pattern?
Comments
Post a Comment