<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title> &#187; module pattern</title>
	<atom:link href="http://www.anzaan.com/tag/module-pattern/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.anzaan.com</link>
	<description></description>
	<lastBuildDate>Sat, 26 Jun 2010 03:29:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Javascript variable scope, private protected and public</title>
		<link>http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/</link>
		<comments>http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/#comments</comments>
		<pubDate>Wed, 27 May 2009 13:30:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[front end]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[javascript varaible scope]]></category>
		<category><![CDATA[module pattern]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=77</guid>
		<description><![CDATA[Private ,public and protected/privileged access of variables and functions in javascript]]></description>
			<content:encoded><![CDATA[<p>Javascript is a tricky language. Since I learned programming with Java, I always find myself trying to find its equivalence in other languages I come across.</p>
<p>I know its bad in that in that it kind of stops me from exploring the potentials provided by other languages in full. Its like going to a Chinese restaurant and eating fried rice everytime because fried rice is the only dish that is close to what I&#8217;m used to eating daily.<br />
There&#8217;s such variety in Chinese food, and yet if I go there and I eat fried-rice evertyime Its a sign I have a bit of a problem opening myself up to new things. And that&#8217;s a big problem.</p>
<p>The world has such diversity in every-aspect imaginable, ( with the exception of mob-justice and mob-mentality which seem to cross all cultural and geographical boundary as it seems), and not being able to appreciate the diversity and learn for it is a great pity.</p>
<p>Back to programming, not all constructs  found in languages are sole property of a  given language. They are  generally abstractions provided by languages to solve problems effectively and those abstractions can be applied in other languages even if they don&#8217;t provide such explicit constructs.</p>
<p>There was a time when I treated javascript like lepers, something to avoid at all cost, except when it was really unavoidable.<br />
But then I had a change of perspective, at a philosophical level -dare I day. &#8216;If I avoid something to such length then I must be shit-scared of it for some reason&#8217;.<br />
And by nature I hate to admit my fears for the fear of being tagged a wussy, a chicken.<br />
Of course I can find things to justify my avoidance of javascript to others without admitting my fear, but how about myself?<br />
What do I tell myself when I go to sleep??<br />
And since I couldn&#8217;t find reasonable arguments to fool myself into good sleep because my rational self always counter-argued that &#8216;you  fear what you don&#8217;t understand&#8217;, and  my arguments against javascript were just my lame attempt to hide my fears , I decided to deal with my fears for once and for good.</p>
<p>And since then I have been quite happy with my javascript experience.</p>
<p>Since I&#8217;m still a Java fan-boy, though I have a feeling that it won&#8217;t be for  too long, Scala! here I come,  I tried to find solution to variable scoping in javascript so that I have more control over objects I create and the API&#8217;s I expose. This has been a big issue due to the need for me to use at least 3-4 third-party libraries to get my job done for the current project I&#8217;m rewriting.<br />
And the project has a massive javascript code-base.</p>
<p>Looking back at the code I did last year makes me cringe. There was no modularity and there was too much interdependency between components and objects.</p>
<p>(Hmm&#8230; component decoupling is entirely another topic for another sleepless night.)</p>
<p>And this time around I decided to do thing the right way &#8211; at least to my best knowledge.</p>
<p>After long hours prowling the internet, finally I managed to understand the trick to accomplish what I wanted.</p>
<p>So here&#8217;s an example of an object with everything pubic, the dumbest example.</p>
<pre class="brush: javascript;">

var Person= function(name ,surname, sex, dob){

this.name=name;
this.surname=surname;
this.sex=sex;
this.dob=dob;

this.getFullName=function(){

return this.surname+&quot;,&quot;+this.name;
}

this.getAge=function(){

return (new Date().getYear() - this.dob.getYear()) ) ;// I'm being lazy here

}

}

// another a little less dumb-looking flavor with prototyping but dumb nonetheless
var Person= function(name ,surname, sex, dob){

this.name=name;
this.surname=surname;
this.sex=sex;
this.dob=dob;
}

Person.prototype.getFullName=function(){
return this.surname+&quot;,&quot;+this.name;
}
Person.prototype.getAge=function(){
return (new Date().getYear() - this.dob.getYear()) ) ;
}
</pre>
<p>All the properties in of the object are accessible to any function/code that instantiates Person object. And getFullName() is nothing more but a handy method for getting both name and surname.<br />
And the calling code can access dob and compute age by itself.<br />
So everything is accessible.</p>
<pre class="brush: javascript;">
var person = new Person('inny', 'minny', 'yes please', new Date(1901, 0, 1) );

var fullname= person.surname+&quot;,&quot;+person.name;

var age=  (new Date().getYear() - person .dob.getYear()) ) ;
</pre>
<p>Of course one can argue that we can differentiate the difference between private and public by using underscore for private properties such as _dob ( as a lot of people insist on doing).</p>
<p>But who are we fooling? That&#8217;s just a convention we use, and if you work in a large team there&#8217;s no guarantee that someone else will not get smart and start mutating the underscored variable and shit might hit the fan depending on how critical the property is.</p>
<p>Instead of developing ad-hoc convention I believe its more ideal to use the best of what a language provides without having to define our own rule which can be broken by anyone who cares to break it. Sometimes I don&#8217;t trust myself,let alone trust others.</p>
<p>So if we need to hide the DOB for privacy reason and only expose the age,  and we need to hide the individual name and surname for some reason, here&#8217;s how its done:</p>
<pre class="brush: javascript;">
var Person= function(name ,surname, sex, dob){

this.sex=sex;

this.getFullName=function(){

return surname+&quot;,&quot;+name;
}

this.getAge=function(){

return  (new Date().getYear() - .dob.getYear()) ) ;

}
}
Person.prototype.getGender=function(){
var sex=this.sex,tolowerCase();
if( sex=='male' || sex=='m' )
return 'male';
else if( sex=='female' || sex=='f' )
rerturn 'female';
else
return 'god knows';

}

Person.prototype.getSpecies=function(){

return 'mammal';
}
</pre>
<p>In the above example, any instantiating code has only access to getFullName() , getAge() functions and &#8217;sex&#8217; variable of person object.<br />
But we allow &#8217;sex&#8217; variable to be declared in two forms, long and short. And we return &#8217;sex&#8217; in  long format with the help o getGender()  helper function.</p>
<p>The above example can be broken down as following;</p>
<p>All variables except sex are private as they are constructor-scoped.<br />
getFullName() and getAge() are privilaged function that have access to private variables name, surname and sex and thus are privileged/protected functions.</p>
<p>getGender() is a public function that has access to public variable sex.<br />
the new getSpecies() is a public function that returns a value that&#8217;s entirely in its own scope.</p>
<p>So, there we have it, private, privileged and public access in javascript.</p>
<p>If we want to use module pattern the above can be modified to:</p>
<pre class="brush: javascript;">
var Person= function(name ,surname, sex, dob){

this.sex=sex;
return{

getFullName:function(){

return surname+&quot;,&quot;+name;
},

getAge:function(){

return  (new Date().getYear() - this.dob.getYear()) ) ;

},
getSpecies:function(){

return 'mammal';
}

}
}
</pre>
<p>An example of creating static object with private and public scope:</p>
<pre class="brush: javascript;">
var Human = function() {

var species = &quot;mammal&quot;;

return {

alert: function(){alert(species);}

};
}();

Human.alert();//displays 'mammal'
</pre>
<p>Here the variable species is private.<br />
The function gets executed immediately due to () at the end of the function definition and will return a public static method alert()</p>
<p>That sums up variable scopes in javascript.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
