flannel 0.0.1 → 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
data/Rakefile CHANGED
@@ -11,7 +11,8 @@ begin
11
11
  gem.homepage = "http://github.com/rubyyot/flannel"
12
12
  gem.authors = ["Jamal Hansen"]
13
13
  gem.rubyforge_project = "flannel"
14
- gem.add_development_dependency 'technicalpickles-shoulda'
14
+ gem.add_dependency 'Hpricot'
15
+ gem.add_development_dependency ['technicalpickles-shoulda', 'mocha']
15
16
 
16
17
  # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
17
18
  end
data/VERSION.yml CHANGED
@@ -1,4 +1,5 @@
1
1
  ---
2
+ :build:
2
3
  :major: 0
3
- :minor: 0
4
- :patch: 1
4
+ :minor: 1
5
+ :patch: 0
@@ -0,0 +1,10 @@
1
+ Feature: Feed conversion
2
+ In order to insert "live" links from rss feeds
3
+ A user of Flannel
4
+ Will quilt feed text markup
5
+
6
+ Scenario: Inserting links from an rss feed
7
+ Given input of "feed" text
8
+ And the necessary feeds
9
+ When I quilt it with flannel
10
+ Then valid html should be produced
@@ -0,0 +1,959 @@
1
+ <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Sergio Pereira : JavaScript-Demystified</title><link>http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx</link><description>Tags: JavaScript-Demystified</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>JavaScript and its love for zeroes</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/09/19/javascript-and-its-love-for-zeroes.aspx</link><pubDate>Sat, 19 Sep 2009 13:54:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:51520</guid><dc:creator>sergiopereira</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/sergio_pereira/rsscomments.aspx?PostID=51520</wfw:commentRss><comments>http://devlicio.us/blogs/sergio_pereira/archive/2009/09/19/javascript-and-its-love-for-zeroes.aspx#comments</comments><description>&lt;div class="note"&gt;
2
+ This post is part of a series called &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx"&gt;
3
+ JavaScript Demystified&lt;/a&gt;.
4
+ &lt;/div&gt;
5
+
6
+ &lt;p&gt;Answer quick. Do you know what date is being created here?&lt;/p&gt;
7
+ &lt;pre name="code" class="js:nogutter"&gt;var year = &amp;#39;2009&amp;#39;, month = &amp;#39;09&amp;#39;, day = &amp;#39;01&amp;#39;;
8
+ var date = new Date(
9
+ parseInt(year),
10
+ parseInt(month),
11
+ parseInt(day)
12
+ ); &lt;/pre&gt;
13
+
14
+ &lt;p&gt;
15
+ At first glance, it wouldn&amp;#39;t surprising that someone guesseed &lt;i&gt;September 1&lt;sup&gt;st&lt;/sup&gt; 2009&lt;/i&gt;.
16
+ However, I&amp;#39;d not be writing this post if that was the correct answer, right?
17
+ &lt;/p&gt;
18
+ &lt;p&gt;
19
+ There&amp;#39;s an interesting and tricky thing with the JavaScript &lt;code&gt;parseInt&lt;/code&gt; function: it
20
+ can parse strings with a numeric value in the decimal radix, but also in other radices. See the
21
+ following examples.
22
+ &lt;/p&gt;
23
+
24
+ &lt;pre name="code" class="js:nogutter"&gt;//passing the radix explicitly
25
+ parseInt(&amp;#39;1011&amp;#39;, 10); // ==&amp;gt; 1011
26
+ parseInt(&amp;#39;1011&amp;#39;, 2); // ==&amp;gt; 11
27
+ parseInt(&amp;#39;1011&amp;#39;, 8); // ==&amp;gt; 521
28
+ parseInt(&amp;#39;1011&amp;#39;, 16); // ==&amp;gt; 4113
29
+ &lt;/pre&gt;
30
+
31
+ &lt;p&gt;Maybe you thought that if you didn&amp;#39;t pass the radix, then it would default to 10 because
32
+ it&amp;#39;s the obvious behavior. Well, no. In JavaScript the default behavior is to try to
33
+ identify one of the literal formats and interpret that. So here&amp;#39;s that in action:&lt;/p&gt;
34
+
35
+ &lt;pre name="code" class="js:nogutter"&gt;//leaving JavaScript on its own
36
+ parseInt(&amp;#39;1011&amp;#39;); // ==&amp;gt; 1011 (decimal literal)
37
+ parseInt(&amp;#39;0x12&amp;#39;); // ==&amp;gt; 18 (hexadecimal literal)
38
+ parseInt(&amp;#39;0511&amp;#39;); // ==&amp;gt; 329 (octal literal)
39
+ parseInt(&amp;#39;0182&amp;#39;); // ==&amp;gt; 1 (whaaaa?!?!)
40
+ &lt;/pre&gt;
41
+
42
+ &lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.09/js_2D00_newyear.png" align="left" alt="" /&gt;
43
+
44
+ &lt;p&gt;
45
+ If you are familiar with the literal notation for integer numbers in JavaScript,
46
+ and after I explained the default behavior of &lt;code&gt;parseInt&lt;/code&gt;, then
47
+ you probaly understood the results shown above. Well, maybe the last one deserves
48
+ some comments.
49
+ &lt;/p&gt;
50
+ &lt;p&gt;
51
+ When JavaScript is parsing the string, if it finds a digit (number or alpha) that is invalid
52
+ in the chosen radix, it stops right there and parses only the portion of the string that
53
+ comes before that digit. So, since we started &lt;code&gt;&amp;#39;0182&amp;#39;&lt;/code&gt; with a leading zero, the
54
+ octal radix is assumed. Then, because &lt;b&gt;8&lt;/b&gt; is not a valid octal digit, only &lt;code&gt;&amp;#39;01&amp;#39;&lt;/code&gt;
55
+ will be parsed, which becomes &lt;b&gt;1&lt;/b&gt;.
56
+ &lt;/p&gt;
57
+
58
+ &lt;div class="note"&gt;&lt;span class="legend"&gt;Tip #1:&lt;/span&gt;
59
+ If there&amp;#39;s any chance the string value you plan to parse into an integer number has
60
+ a leading zero (or a less likely &lt;b&gt;0x&lt;/b&gt;,) then be safe and pass the radix parameter
61
+ to your &lt;code&gt;parseInt&lt;/code&gt; call. If you&amp;#39;re extra paranoid, then always pass the radix.
62
+ &lt;/div&gt;
63
+
64
+
65
+ &lt;h3&gt;Back to our original question&lt;/h3&gt;
66
+
67
+ &lt;p&gt;Armed with the clarification made above, we can expand our example like this:&lt;/p&gt;
68
+ &lt;pre name="code" class="js:nogutter"&gt;//given:
69
+ var year = &amp;#39;2009&amp;#39;, month = &amp;#39;09&amp;#39;, day = &amp;#39;01&amp;#39;;
70
+ // then the following statement:
71
+ var date = new Date(
72
+ parseInt(year),
73
+ parseInt(month),
74
+ parseInt(day)
75
+ );
76
+ //...is equivalent to:
77
+ var date = new Date(
78
+ 2009,
79
+ 0, // ===&amp;gt; oopsie
80
+ 1
81
+ ); &lt;/pre&gt;
82
+
83
+ &lt;p&gt;Hmmm, a zero in the month parameter. Will we have an error here? No, here comes the second potential surprise of this post.&lt;/p&gt;
84
+
85
+ &lt;div class="note"&gt;&lt;span class="legend"&gt;Tip #2:&lt;/span&gt;
86
+ When creating a new date using &lt;code&gt;new Date(year, month, day)&lt;/code&gt;, the &lt;code&gt;month&lt;/code&gt;
87
+ parameter, and &lt;b&gt;only&lt;/b&gt; the month parameter is zero-based (0 to 11).
88
+ &lt;/div&gt;
89
+
90
+ &lt;p&gt;So, in case the tips and the picture in this text were not enough to help you guessing the
91
+ date being created, here goes another completely gratuitous one with the answer.
92
+
93
+ &lt;p&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.09/js_2D00_newyear2.png" alt="" /&gt;&lt;/p&gt;
94
+ &lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=51520" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Development/default.aspx">Development</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Tips-and-Tricks/default.aspx">Tips-and-Tricks</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx">JavaScript-Demystified</category></item><item><title>JavaScript: Not your father's inheritance model - Part 2</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/06/12/javascript-not-your-father-s-inheritance-model-part-2.aspx</link><pubDate>Fri, 12 Jun 2009 23:26:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:47885</guid><dc:creator>sergiopereira</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/sergio_pereira/rsscomments.aspx?PostID=47885</wfw:commentRss><comments>http://devlicio.us/blogs/sergio_pereira/archive/2009/06/12/javascript-not-your-father-s-inheritance-model-part-2.aspx#comments</comments><description>&lt;div class="note"&gt;
95
+ This post is part of a series called &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx"&gt;
96
+ JavaScript Demystified&lt;/a&gt;.
97
+ &lt;/div&gt;
98
+
99
+ &lt;p&gt;&lt;i&gt;This particular chapter is further divided in two parts. Read &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2009/06/12/javascript-not-your-father-s-inheritance-model-part-1.aspx"&gt;Part 1&lt;/a&gt;.&lt;/i&gt;&lt;/p&gt;
100
+
101
+
102
+
103
+
104
+ &lt;h3&gt;Build your own hierarchy&lt;/h3&gt;
105
+
106
+ &lt;p&gt;Let&amp;#39;s pretend we are building some scripts that deal with musical instruments. We could define our own &lt;code&gt;Guitar&lt;/code&gt; &lt;strike&gt;class&lt;/strike&gt; type like this:
107
+ &lt;/p&gt;
108
+
109
+ &lt;pre name="code" class="js:nogutter"&gt;//The constructor
110
+ function Guitar(brand, model) {
111
+ this.brand = brand;
112
+ this.model = model;
113
+ this.strings = [&amp;#39;E&amp;#39;, &amp;#39;A&amp;#39;, &amp;#39;D&amp;#39;, &amp;#39;G&amp;#39;, &amp;#39;B&amp;#39;, &amp;#39;e&amp;#39;];
114
+ }
115
+
116
+ //Instance methods
117
+ Guitar.prototype = {
118
+ play: function (chord) {
119
+ alert(&amp;#39;Playing &amp;#39; + chord);
120
+ },
121
+ toString: function () {
122
+ return &amp;#39;(Guitar: &amp;#39; +
123
+ this.brand + &amp;#39; &amp;#39; +
124
+ this.model + &amp;#39;)&amp;#39;;
125
+ }
126
+ };
127
+
128
+ var guitar1 = new Guitar(&amp;#39;Gibson&amp;#39;, &amp;#39;Les Paul&amp;#39;);&lt;/pre&gt;
129
+
130
+ &lt;p&gt;What may not be apparent by just looking at the code for the first time is that &lt;code&gt;guitar1&lt;/code&gt;&amp;#39;s Prototype will be &lt;code&gt;Guitar.prototype&lt;/code&gt;, which means that &lt;code&gt;guitar1&lt;/code&gt; inherits from &lt;code&gt;Guitar.prototype&lt;/code&gt;. Also &lt;code&gt;guitar1.constructor === Guitar&lt;/code&gt;.
131
+ &lt;/p&gt;
132
+
133
+ &lt;p&gt;When the last line in the above example is executed, the JavaScript runtime will take care of initializing a new object that has &lt;code&gt;Guitar.prototype&lt;/code&gt; as its Prototype and makes its &lt;code&gt;constructor&lt;/code&gt; property point to the &lt;code&gt;Guitar&lt;/code&gt; function.
134
+ &lt;/p&gt;
135
+
136
+ &lt;p&gt;But what if we want to create a different type of guitars and still reuse the existing &lt;code&gt;Guitar&lt;/code&gt; type. We could do this:
137
+ &lt;/p&gt;
138
+
139
+ &lt;pre name="code" class="js:nogutter"&gt;function BassGuitar(brand, model) {
140
+ //call the constructor of our base type
141
+ Guitar.apply(this, [brand, model] );
142
+ //change or add anything we wish
143
+ this.strings = [&amp;#39;E&amp;#39;, &amp;#39;A&amp;#39;, &amp;#39;D&amp;#39;, &amp;#39;G&amp;#39;];
144
+ }
145
+
146
+ //Copy the Prototype of our base type
147
+ BassGuitar.prototype = Object.create(Guitar.prototype);
148
+
149
+ //Override whatever we want:
150
+ BassGuitar.prototype.toString = function () {
151
+ return &amp;#39;(BassGuitar: &amp;#39; +
152
+ this.brand + &amp;#39; &amp;#39; +
153
+ this.model + &amp;#39;)&amp;#39;;
154
+ };
155
+
156
+ var bass1 = new BassGuitar(&amp;#39;Peavey&amp;#39;, &amp;#39;Cirrus&amp;#39;);
157
+ bass1.toString(); //=&amp;gt; &amp;#39;(BassGuitar: Peavey Cirrus)&amp;#39;
158
+ alert(bass1.strings); //=&amp;gt; [ &amp;#39;E&amp;#39;, &amp;#39;A&amp;#39;, &amp;#39;D&amp;#39;, &amp;#39;G&amp;#39; ]&lt;/pre&gt;
159
+
160
+ &lt;p style="text-align:center;"&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.06/js_5F00_inh_5F00_5.png" alt="" /&gt;&lt;/p&gt;
161
+
162
+
163
+ &lt;p&gt;&lt;b&gt;But there&amp;#39;s a problem with the above code.&lt;/b&gt; There isn&amp;#39;t a method &lt;code&gt;Object.create()&lt;/code&gt;. Yeah, that&amp;#39;s one of the design omissions in JavaScript. Any prototype-based language needs an easy way to let use create objects from other objects.
164
+ &lt;/p&gt;
165
+
166
+ &lt;p&gt;Thankfully JavaScript is also dynamically typed, so we can add that function ourselves. Here I&amp;#39;m borrowing from &lt;a href="http://javascript.crockford.com/prototypal.html"&gt;Douglas Crockford&lt;/a&gt;.
167
+ &lt;/p&gt;
168
+
169
+ &lt;pre name="code" class="js:nogutter"&gt;//add this to the very beginning of your scripts
170
+ if (typeof Object.create !== &amp;#39;function&amp;#39;) {
171
+ Object.create = function (o) {
172
+ function F() {}
173
+ F.prototype = o;
174
+ return new F();
175
+ };
176
+ }&lt;/pre&gt;
177
+
178
+ &lt;p&gt;I&amp;#39;ll leave the interpretation of the above function as an exercise to the reader. Once you understand what it is doing you will have mastered prototypes and constructors.
179
+ &lt;/p&gt;
180
+
181
+ &lt;h3&gt;Handy Prototype tricks&lt;/h3&gt;
182
+
183
+ &lt;p&gt;Knowing what we know now and once again leveraging JavaScript&amp;#39;s dynamism we can fix one of the things that has always annoyed me in JavaScript: the lack of a &lt;code&gt;trim()&lt;/code&gt; method on strings.
184
+ &lt;/p&gt;
185
+
186
+ &lt;pre name="code" class="js:nogutter"&gt;String.prototype.trim = function () {
187
+ return this.replace( /^\s*(\S*(\s+\S+)*)\s*$/, &amp;quot;$1&amp;quot;);
188
+ };
189
+ var text = &amp;#39; some user-entered value &amp;#39;;
190
+ alert( text.trim() ); // =&amp;gt; &amp;#39;some user-entered value&amp;#39;&lt;/pre&gt;
191
+
192
+ &lt;p&gt;How about an easy way to pad numbers with zeroes?
193
+ &lt;/p&gt;
194
+
195
+ &lt;pre name="code" class="js:nogutter"&gt;Number.prototype.padLeft = function (width) {
196
+ var text = this.toString();
197
+ for(; text.length &amp;lt; width; ){
198
+ text = &amp;#39;0&amp;#39; + text;
199
+ }
200
+ return text;
201
+ };
202
+
203
+ var num = 1234;
204
+ alert(num.padLeft(6)); // =&amp;gt; 001234&lt;/pre&gt;
205
+
206
+
207
+ &lt;h3&gt;Why do I need to know all this stuff?&lt;/h3&gt;
208
+
209
+ &lt;p&gt;Well, you don&amp;#39;t. But why even bother writing JavaScript code if you&amp;#39;re not willing to learn how it works? &lt;/p&gt;
210
+
211
+ &lt;p&gt;As we have been seeing during this series, JavaScript bears only some syntax similarities with C# or Java. Underneath the surface it has been designed very differently. The web is riddled with attempts to mimic class-based inheritance in JavaScript only because programmers don&amp;#39;t want to learn and leverage prototype-based logic.&lt;/p&gt;
212
+
213
+ &lt;p&gt;My humble advice is that you will feel happier and smarter if you chose to learn how to use the language as it was intended.&lt;/p&gt;
214
+
215
+ &lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=47885" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx">JavaScript-Demystified</category></item><item><title>JavaScript: Not your father's inheritance model - Part 1</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/06/12/javascript-not-your-father-s-inheritance-model-part-1.aspx</link><pubDate>Fri, 12 Jun 2009 23:03:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:47882</guid><dc:creator>sergiopereira</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/sergio_pereira/rsscomments.aspx?PostID=47882</wfw:commentRss><comments>http://devlicio.us/blogs/sergio_pereira/archive/2009/06/12/javascript-not-your-father-s-inheritance-model-part-1.aspx#comments</comments><description>&lt;div class="note"&gt;
216
+ This post is part of a series called &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx"&gt;
217
+ JavaScript Demystified&lt;/a&gt;.
218
+ &lt;/div&gt;
219
+
220
+ &lt;p&gt;&lt;i&gt;This particular chapter is further divided in two parts. Read &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2009/06/12/javascript-not-your-father-s-inheritance-model-part-2.aspx"&gt;Part 2&lt;/a&gt;.&lt;/i&gt;&lt;/p&gt;
221
+
222
+
223
+
224
+ &lt;p&gt;In a previous installment in this series we saw how we could create constructor functions in JavaScript. Back then I just mentioned that we don&amp;#39;t have classes in JavaScript and that there&amp;#39;s this weird &lt;code&gt;prototype&lt;/code&gt; property in every object.
225
+ &lt;/p&gt;
226
+
227
+ &lt;p&gt;Let&amp;#39;s dig into those concepts a little more and try to understand how inheritance is achieved in JavaScript.
228
+ &lt;/p&gt;
229
+
230
+ &lt;h3&gt;Inheritance as we often know it&lt;/h3&gt;
231
+
232
+ &lt;p&gt;For myself and probably the majority of you reading this blog, inheritance in an Object Oriented programming language is directly associated with the concept of classes.
233
+ &lt;/p&gt;
234
+
235
+ &lt;p&gt;When we work with C#, VB, Java, Ruby, and many other popular programming languages, each of our objects is of some type, which is represented by a class. Our objects automatically inherit functionality from their associated class often called base or super class, and any other classes that the base class itself is associated with (i.e. derives from.)
236
+ &lt;/p&gt;
237
+ &lt;p&gt;That&amp;#39;s nothing new to you, I&amp;#39;m sure. I&amp;#39;m just re-hashing that in the previous paragraph to make a comparison later. Let&amp;#39;s call this model class-based inheritance.
238
+ &lt;/p&gt;
239
+
240
+
241
+ &lt;h3&gt;That&amp;#39;s not the end of the story&lt;/h3&gt;
242
+
243
+ &lt;p&gt;This may come as a surprise to some people, but class-based inheritance is not the only way to obtain Object Oriented inheritance (by saying Object Oriented I automatically excluded those of you that thought Copy/Paste Inheritance was one of them.)
244
+ &lt;/p&gt;
245
+
246
+ &lt;p&gt;It just so happens that the JavaScript language designers chose another inheritance model. And they are not alone in that choice. By opting for a &lt;a href="http://en.wikipedia.org/wiki/Prototype-based_programming"&gt;prototype-based inheritance model&lt;/a&gt; , JavaScript joined the ranks of other programming languages such as &lt;a href="http://selflanguage.org/"&gt;Self&lt;/a&gt; , &lt;a href="http://www.lua.org/"&gt;Lua&lt;/a&gt; , and &lt;a href="http://prog.vub.ac.be/research/agora/"&gt;Agora&lt;/a&gt;.
247
+ &lt;/p&gt;
248
+
249
+
250
+ &lt;h3&gt;The prototype is the king&lt;/h3&gt;
251
+
252
+ &lt;p&gt;Objects in JavaScript don&amp;#39;t inherit from classes; they inherit straight from other objects. The object they inherit from is called their Prototype (I&amp;#39;m using a capital P here to avoid confusion down the line.) The object&amp;#39;s Prototype is assigned right at construction time.
253
+ &lt;/p&gt;
254
+
255
+ &lt;p&gt;You may be intrigued and say: But when I create my objects I don&amp;#39;t remember specifying any Prototype stuff. What gives?
256
+ &lt;/p&gt;
257
+
258
+ &lt;p&gt;Let&amp;#39;s see what happens then. When you create a plain Object using either of the following syntaxes
259
+ &lt;/p&gt;
260
+
261
+ &lt;pre name="code" class="js:nogutter"&gt;var obj1 = new Object();
262
+ obj1.name = &amp;#39;box&amp;#39;
263
+ //or
264
+ var obj2 = { name: &amp;#39;door&amp;#39; };
265
+ &lt;/pre&gt;
266
+
267
+ &lt;p&gt;JavaScript will automatically assign a Prototype to each of these objects. This prototype will be &lt;code&gt;Object.prototype&lt;/code&gt;.
268
+ &lt;/p&gt;
269
+
270
+ &lt;p style="text-align:center;"&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.06/js_5F00_inh_5F00_1.png" alt="" /&gt;&lt;/p&gt;
271
+
272
+ &lt;p&gt;Similarly, let&amp;#39;s see what happens with a few of the other object types in JavaScript.
273
+ &lt;/p&gt;
274
+
275
+ &lt;p style="text-align:center;"&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.06/js_5F00_inh_5F00_2.png" alt="" /&gt;&lt;/p&gt;
276
+
277
+ &lt;p&gt;The Prototype objects is how every object in JavaScript is born with inherited functionality. For example, the &lt;code&gt;substring()&lt;/code&gt; method that every &lt;code&gt;String&lt;/code&gt; object has is a method defined in the object &lt;code&gt;String.Prototype&lt;/code&gt;.
278
+ &lt;/p&gt;
279
+
280
+ &lt;p style="text-align:center;"&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.06/js_5F00_inh_5F00_3.png" alt="" /&gt;&lt;/p&gt;
281
+
282
+ &lt;p&gt;The prototype objects themselves also inherit from &lt;code&gt;Object.prototype&lt;/code&gt;, that&amp;#39;s how every object of any type has a &lt;code&gt;toString()&lt;/code&gt; method.
283
+ &lt;/p&gt;
284
+
285
+ &lt;p style="text-align:center;"&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.06/js_5F00_inh_5F00_4.png" alt="" /&gt;&lt;/p&gt;
286
+
287
+ &lt;p&gt;When you try to access &lt;code&gt;1234.constructor&lt;/code&gt;, as an example, the runtime will look for a &lt;code&gt;constructor&lt;/code&gt; property on our object (the number 1234). It doesn&amp;#39;t have one so the next step taken is to check if that object&amp;#39;s Prototype has it. The Prototype for 1234 is &lt;code&gt;Number.prototype&lt;/code&gt; and it doesn&amp;#39;t have that property either. The runtime then looks on the Prototype of &lt;code&gt;Number.prototype&lt;/code&gt;, which is &lt;code&gt;Object.prototype&lt;/code&gt;. That last object does have a &lt;code&gt;constructor&lt;/code&gt; property, so that is returned. If it didn&amp;#39;t, &lt;code&gt;undefined&lt;/code&gt; would have been returned instead.
288
+ &lt;/p&gt;
289
+
290
+ &lt;p&gt;In &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2009/06/12/javascript-not-your-father-s-inheritance-model-part-2.aspx"&gt;Part 2&lt;/a&gt; we will see how to create our own Prototypes.
291
+ &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=47882" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx">JavaScript-Demystified</category></item><item><title>JavaScript: Avoid the Evil eval</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/03/31/javascript-avoid-the-evil-eval.aspx</link><pubDate>Tue, 31 Mar 2009 22:23:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:45311</guid><dc:creator>sergiopereira</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/sergio_pereira/rsscomments.aspx?PostID=45311</wfw:commentRss><comments>http://devlicio.us/blogs/sergio_pereira/archive/2009/03/31/javascript-avoid-the-evil-eval.aspx#comments</comments><description>&lt;div class="note"&gt;
292
+ This post is part of a series called &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx"&gt;JavaScript Demystified&lt;/a&gt;.
293
+ &lt;/div&gt;
294
+ &lt;p&gt;
295
+ I&amp;#39;m pretty sure by now you have heard at least once that &lt;a href="http://blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx"&gt;&lt;code&gt;eval&lt;/code&gt; is evil&lt;/a&gt;. Some
296
+ nuggets from Eric Lippert&amp;#39;s post:
297
+ &lt;/p&gt;
298
+
299
+ &lt;blockquote&gt;if you are considering using eval then there is probably a better way&lt;/blockquote&gt;
300
+ &lt;blockquote&gt;People, eval starts a compiler.&lt;/blockquote&gt;
301
+
302
+ &lt;p&gt;
303
+ I&amp;#39;m also pretty sure I don&amp;#39;t need to tell you that anytime you have an explicit &lt;code&gt;eval()&lt;/code&gt; in your
304
+ code, there&amp;#39;s a good chance it&amp;#39;s there because
305
+ &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2008/05/03/give-javascript-a-chance.aspx"&gt;you&amp;#39;re not taking JavaScript seriously&lt;/a&gt; yet.
306
+ &lt;/p&gt;
307
+ &lt;pre name="code" class="js"&gt;//mandatory square brackets notation example
308
+ //------------------------------------------
309
+ var myObject = new MyObject();
310
+ var prop1 = eval( &amp;#39;myObject.&amp;#39; + somePropertyName ); // BAD!
311
+ var prop2 = myObject[ somePropertyName ]; // Better&lt;/pre&gt;
312
+
313
+ &lt;h3&gt;That&amp;#39;s not the end of all &lt;code&gt;eval()&lt;/code&gt;&lt;/h3&gt;
314
+ &lt;p&gt;
315
+ At this point some people might be feeling relieved: &lt;i&gt;&amp;quot;Phew! That was
316
+ easier than it sounded. Getting rid of eval is a piece of cake.&amp;quot;&lt;/i&gt; Well,
317
+ I&amp;#39;m not going to say it&amp;#39;s significantly harder than that, but we&amp;#39;re not
318
+ done prunning &lt;code&gt;eval()&lt;/code&gt; from our code just yet.
319
+ &lt;/p&gt;
320
+ &lt;p&gt;
321
+ You see, &lt;code&gt;eval()&lt;/code&gt; is like that coward opponent that sneaks in the
322
+ dark to attack you from behind. Let&amp;#39;s find some of &lt;code&gt;eval&lt;/code&gt;&amp;#39;s
323
+ favorite hiding places.
324
+ &lt;/p&gt;
325
+
326
+ &lt;h3&gt;There&amp;#39;s a time when you need a timer&lt;/h3&gt;
327
+ &lt;p&gt;
328
+ Two very popular JavaScript functions used to create timers are &lt;code&gt;setTimeout()&lt;/code&gt; and
329
+ &lt;code&gt;setInterval()&lt;/code&gt;. Here&amp;#39;s how you still find code being written to use them.
330
+ &lt;/p&gt;
331
+ &lt;pre name="code" class="js"&gt;function doSomething(someValue){
332
+ //...
333
+ }
334
+
335
+ setTimeout(&amp;quot;doSomething(&amp;#39;3 seconds elapsed. Time is up.&amp;#39;);&amp;quot;, 3000);&lt;/pre&gt;
336
+
337
+
338
+ &lt;p&gt;
339
+ As it turns out, this is just another occurrence of &lt;code&gt;eval()&lt;/code&gt; revealing
340
+ how incompetent we can still be in this programming language. Here&amp;#39;s
341
+ a better way to write that code.
342
+ &lt;/p&gt;
343
+ &lt;pre name="code" class="js"&gt;setTimeout( function(){
344
+ doSomething(&amp;#39;3 seconds elapsed. Time is up.&amp;#39;);
345
+ },
346
+ 3000);&lt;/pre&gt;
347
+
348
+ &lt;h3&gt;Thank God I didn&amp;#39;t know functions had constructors&lt;/h3&gt;
349
+ &lt;p&gt;
350
+ The other secret place that &lt;code&gt;eval()&lt;/code&gt; likes to hang out is
351
+ in the &lt;code&gt;Function&lt;/code&gt; constructor. Fortunately this isn&amp;#39;t exactly a
352
+ popular way of creating functions. I&amp;#39;ll say it: I didn&amp;#39;t even know about
353
+ this constructor until less than a couple of years ago.
354
+ &lt;/p&gt;
355
+ &lt;p&gt;
356
+ So, in case you don&amp;#39;t know what I&amp;#39;m talking about here, I&amp;#39;ll show you
357
+ how to use the function constructor just to imemdiately tell you to not do it.
358
+ &lt;/p&gt;
359
+
360
+ &lt;pre name="code" class="js"&gt;var sum = new Function(&amp;#39;op1&amp;#39;, &amp;#39;op2&amp;#39;, &amp;#39;return op1 + op2;&amp;#39;);
361
+ var result = sum(10, 20); // ==&amp;gt; 30&lt;/pre&gt;
362
+
363
+ &lt;p&gt;
364
+ The above code is roughly equivalent to the explicit &lt;code&gt;eval()&lt;/code&gt; usage below.
365
+ &lt;/p&gt;
366
+ &lt;pre name="code" class="js"&gt;eval(&amp;quot;var sum = function (op1, op2) { return op1 + op2; }&amp;quot;);
367
+ var result = sum(10, 20); // ==&amp;gt; 30&lt;/pre&gt;
368
+ &lt;p&gt;
369
+ We don&amp;#39;t come up with the need to use the function constructor often, but I&amp;#39;ll
370
+ admit that when we do, it&amp;#39;s usually hard to replace it with another way that
371
+ doesn&amp;#39;t use &lt;code&gt;eval()&lt;/code&gt;.
372
+ &lt;/p&gt;
373
+
374
+ &lt;div class="note"&gt;&lt;span class="legend"&gt;Minor update:&lt;/span&gt;
375
+ I was doing some snooping around with Firebug and Reflector and found that WebUIValidation.js (embedded in System.Web.dll)
376
+ does use &lt;code&gt;eval()&lt;/code&gt; in some ways that I just pointed out to be unnecessary. If that is of any comfort to anyone
377
+ that has done the same in the past, there you have probably the largest deployment of misused &lt;code&gt;eval()&lt;/code&gt; I know of.
378
+ &lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=45311" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx">JavaScript-Demystified</category></item><item><title>JavaScript, inner functions and private members</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/02/24/javascript-inner-functions-and-private-members.aspx</link><pubDate>Tue, 24 Feb 2009 14:31:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:44569</guid><dc:creator>sergiopereira</dc:creator><slash:comments>15</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/sergio_pereira/rsscomments.aspx?PostID=44569</wfw:commentRss><comments>http://devlicio.us/blogs/sergio_pereira/archive/2009/02/24/javascript-inner-functions-and-private-members.aspx#comments</comments><description>&lt;div class="note"&gt;
379
+ This post is part of a series called &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx"&gt;JavaScript Demystified&lt;/a&gt;.
380
+ &lt;/div&gt;
381
+
382
+ &lt;p&gt;
383
+ In &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2009/02/23/javascript-time-to-grok-closures.aspx"&gt;our last installment&lt;/a&gt; in this short JavaScript series we
384
+ took a look at closures. In some of the examples, we saw functions being
385
+ declared (and returned) inside other functions. The capability of declaring
386
+ a function inside another one is not common to all languages &amp;mdash; C#
387
+ only added this ability in version 2.0, via anonymous delegates.
388
+ &lt;/p&gt;
389
+
390
+ &lt;p&gt;
391
+ Here&amp;#39;s an example of inner functions in use.
392
+ &lt;/p&gt;
393
+
394
+ &lt;pre name="code" class="js"&gt;function printPriceLong(name, price, quantity, currency) {
395
+ var formatCurrency = function(value) {
396
+ return value + &amp;#39; &amp;#39; + currency;
397
+ };
398
+ return &amp;#39;Item: &amp;#39; + name + &amp;#39;\n&amp;#39; +
399
+ &amp;#39;Unit price: &amp;#39; + formatCurrency(price) + &amp;#39;\n&amp;#39; +
400
+ &amp;#39;Quantity: &amp;#39; + quantity + &amp;#39;\n&amp;#39; +
401
+ &amp;#39;TOTAL: &amp;#39; + formatCurrency(price * quantity);
402
+ }
403
+
404
+ alert( printPriceLong(&amp;#39;100g Toblerone bar&amp;#39;, 2.09, 3, &amp;#39;USD&amp;#39;) );
405
+ /* =&amp;gt;
406
+ Item: 100g Toblerone bar
407
+ Unit price: 2.09 USD
408
+ Quantity: 3
409
+ TOTAL: 6.27 USD
410
+ */&lt;/pre&gt;
411
+
412
+ &lt;p&gt;
413
+ If we try to call &lt;code&gt;formatCurrency&lt;/code&gt; from anywhere outside
414
+ of &lt;code&gt;printPriceLong&lt;/code&gt; we are going to cause an error because
415
+ &lt;code&gt;formatCurrency&lt;/code&gt; is scoped only inside its parent function.
416
+ &lt;/p&gt;
417
+ &lt;p&gt;
418
+ In this example we can also see closures in action once again. The
419
+ &lt;code&gt;currency&lt;/code&gt; value is referenced inside &lt;code&gt;formatCurrency&lt;/code&gt;
420
+ but it&amp;#39;s declared in it&amp;#39;s parent. It&amp;#39;s a short-lived closure, mind you,
421
+ because we are not returning that inner function. It&amp;#39;s discarded as soon
422
+ as the parent function exits.
423
+ &lt;/p&gt;
424
+
425
+
426
+ &lt;h3&gt;Who said JavaScript objects can&amp;#39;t have private members?&lt;/h3&gt;
427
+
428
+ &lt;p&gt;
429
+ Developers sometimes get upset when they realize that anyone has
430
+ read and write access to the fields and methods of their JavaScript objects.
431
+ Most of us are used to work with languages that allow us to declare
432
+ some of our object&amp;#39;s members out of reach for the calling code. We
433
+ say that these members are private and we don&amp;#39;t want anyone changing
434
+ or even seeing them.
435
+ &lt;/p&gt;
436
+
437
+ &lt;p&gt;
438
+ Well, this is not exactly true. If you must have private members in
439
+ your JavaScript objects, you can. Inner functions and closures will
440
+ come to our rescue.
441
+ &lt;/p&gt;
442
+
443
+ &lt;p&gt;
444
+ Let&amp;#39;s build on our previous example. Let&amp;#39;s create an &lt;code&gt;OrderItem&lt;/code&gt;
445
+ object that will hold those values (name, price, etc.) Let&amp;#39;s assume we
446
+ do not want anyone changing the object&amp;#39;s price without changing the
447
+ currency at the same time (to ensure some level of consistency.) We
448
+ could code our object like this:
449
+ &lt;/p&gt;
450
+
451
+ &lt;pre name="code" class="js"&gt;function OrderItem(productName, price, quantity, currency) {
452
+ //regular properties
453
+ this.name = productName;
454
+ this.quantity = quantity;
455
+
456
+ //read accessors
457
+ this.getCurrency = function(){ return currency; };
458
+ this.getPrice = function(){ return price; };
459
+ //write accessor
460
+ this.setPrice = function(newPrice, newCurrency){
461
+ if(typeof price !== &amp;#39;number&amp;#39; || price &amp;lt; 0){
462
+ throw { message:&amp;#39;invalid price&amp;#39; };
463
+ }
464
+ if(typeof newCurrency !== &amp;#39;string&amp;#39;){
465
+ throw { message:&amp;#39;invalid currency&amp;#39; };
466
+ }
467
+ price = newPrice;
468
+ currency = newCurrency;
469
+ };
470
+
471
+ //a private function
472
+ var formatCurrency = function(value) {
473
+ return value + &amp;#39; &amp;#39; + currency;
474
+ };
475
+
476
+ //methods that need private members
477
+ this.getUnitPriceString = function(){
478
+ return formatCurrency(price);
479
+ };
480
+ this.getTotalPriceString = function(){
481
+ return formatCurrency(price * quantity);
482
+ };
483
+ }
484
+
485
+ OrderItem.prototype = {
486
+ //overriding the string representation of the object
487
+ toString: function(){
488
+ return &amp;#39;Item: &amp;#39; + this.name + &amp;#39;\n&amp;#39; +
489
+ &amp;#39;Unit price: &amp;#39; + this.getUnitPriceString() + &amp;#39;\n&amp;#39; +
490
+ &amp;#39;Quantity: &amp;#39; + this.quantity + &amp;#39;\n&amp;#39; +
491
+ &amp;#39;TOTAL: &amp;#39; + this.getTotalPriceString();
492
+ }
493
+ };&lt;/pre&gt;
494
+
495
+ &lt;p&gt;
496
+ That seems a bit long, but hopefully we can understand what&amp;#39;s going on here.
497
+ We are letting &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;quantity&lt;/code&gt; be regular
498
+ read/write properties but we never defined properties for &lt;code&gt;price&lt;/code&gt;
499
+ or &lt;code&gt;currency&lt;/code&gt;. We made those two values accessible via the
500
+ &lt;code&gt;getPrice&lt;/code&gt; and &lt;code&gt;getCurrency&lt;/code&gt; methods, respectively.
501
+ &lt;/p&gt;
502
+
503
+ &lt;p&gt;
504
+ The trick here is that both &lt;code&gt;getPrice&lt;/code&gt;
505
+ and &lt;code&gt;getCurrency&lt;/code&gt; are defined inside our constructor
506
+ function so they have access to the local variables &lt;code&gt;price&lt;/code&gt;
507
+ and &lt;code&gt;currency&lt;/code&gt;. They have access to these variables even
508
+ after the constructor returns (thank you closures.)
509
+ &lt;/p&gt;
510
+
511
+ &lt;p&gt;
512
+ The same can be said for the &lt;code&gt;setPrice&lt;/code&gt; method. We
513
+ will use this method when we need to change the object&amp;#39;s price.
514
+ It will force us to also provide a currency.
515
+ &lt;/p&gt;
516
+
517
+ &lt;p&gt;
518
+ I&amp;#39;ll leave the explanation of the methods &lt;code&gt;getUnitPriceString&lt;/code&gt;
519
+ and &lt;code&gt;getTotalPriceString&lt;/code&gt; as an exercise for you.
520
+ &lt;/p&gt;
521
+
522
+ &lt;p&gt;
523
+ Let&amp;#39;s instantiate one of these objects and see it in action.
524
+ &lt;/p&gt;
525
+
526
+ &lt;pre name="code" class="js:nogutter"&gt;var item = new OrderItem(&amp;#39;100g Toblerone bar&amp;#39;, 2.09, 3, &amp;#39;USD&amp;#39;);
527
+ //public methods:
528
+ alert( item.getUnitPriceString() );
529
+ // =&amp;gt; &amp;#39;2.09 USD&amp;#39;
530
+ alert( item.getTotalPriceString() );
531
+ // =&amp;gt; &amp;#39;6.27 USD&amp;#39;
532
+ alert(item); //this will use the toString() method
533
+ /* =&amp;gt;
534
+ Item: 100g Toblerone bar
535
+ Unit price: 2.09 USD
536
+ Quantity: 3
537
+ TOTAL: 6.27 USD
538
+ */
539
+
540
+ //changing private fields
541
+ item.setPrice(1.11, &amp;#39;EUR&amp;#39;);
542
+ alert( item );
543
+ /* =&amp;gt;
544
+ Item: 100g Toblerone bar
545
+ Unit price: 1.11 EUR &amp;lt;-- it worked!
546
+ Quantity: 3
547
+ TOTAL: 3.33 EUR
548
+ */
549
+
550
+ //proving that price is not a field
551
+ item.price = &amp;#39;5.00&amp;#39;;
552
+ alert( item.getUnitPriceString() );
553
+ // =&amp;gt; &amp;#39;1.11 EUR&amp;#39; &amp;lt;-- Gotcha, smart pants!
554
+
555
+ item.setPrice(2);
556
+ //ERROR: message = &amp;#39;invalid currency&amp;#39;
557
+ alert( item.formatCurrency(1.23) );
558
+ //ERROR: item.formatCurrency is not a function&lt;/pre&gt;
559
+
560
+ &lt;h3&gt;And what am I supposed to do with this information?&lt;/h3&gt;
561
+
562
+ &lt;p&gt;
563
+ I have yet to find the need to use private members in my
564
+ JavaScript objects. Maybe that&amp;#39;s because I am not shipping
565
+ any JavaScript library with complex enough objects.
566
+ &lt;/p&gt;
567
+ &lt;p&gt;
568
+ I think it&amp;#39;s nice to know that you can create those off-limits
569
+ values in your object. Hopefully when the need for such thing
570
+ arises, we won&amp;#39;t just say &lt;i&gt;Oh, no! Can&amp;#39;t do that!&lt;/i&gt;.
571
+ &lt;/p&gt;
572
+ &lt;p&gt;
573
+ What about you? Have you found a use for private members in
574
+ your JavaScript code? How did you get around or implemented it?
575
+ &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=44569" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx">JavaScript-Demystified</category></item><item><title>JavaScript, time to grok closures</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/02/23/javascript-time-to-grok-closures.aspx</link><pubDate>Mon, 23 Feb 2009 13:28:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:44499</guid><dc:creator>sergiopereira</dc:creator><slash:comments>18</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/sergio_pereira/rsscomments.aspx?PostID=44499</wfw:commentRss><comments>http://devlicio.us/blogs/sergio_pereira/archive/2009/02/23/javascript-time-to-grok-closures.aspx#comments</comments><description>&lt;div class="note"&gt;
576
+ This post is part of a series called &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx"&gt;JavaScript Demystified&lt;/a&gt;.
577
+ &lt;/div&gt;
578
+
579
+ &lt;p&gt;
580
+ When I wrote about &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx"&gt;functions in JavaScript&lt;/a&gt; I mentioned that
581
+ functions are more than just a block of code:
582
+ &lt;/p&gt;
583
+ &lt;blockquote&gt;
584
+ &lt;code&gt;Function&lt;/code&gt; is a standard data type in JavaScript, an object indeed; you can pass them around and copy them.
585
+ &lt;/blockquote&gt;
586
+
587
+ &lt;p&gt;
588
+ Let&amp;#39;s take a look at this small sample of a function that creates
589
+ and returns another function. The returned function accepts one
590
+ string argument and returns another string repeating the argument a number of times.
591
+ &lt;/p&gt;
592
+
593
+ &lt;pre name="code" class="js"&gt;function makeRepeater(times){
594
+ return function(text){
595
+ var message = &amp;#39;&amp;#39;;
596
+ for (var i=0; i &amp;lt; times; i++) {
597
+ message += text + &amp;#39; &amp;#39;;
598
+ }
599
+ return message;
600
+ };
601
+ }&lt;/pre&gt;
602
+
603
+ &lt;p&gt;
604
+ Let&amp;#39;s now write some code that uses that function.
605
+ &lt;/p&gt;
606
+
607
+ &lt;pre name="code" class="js"&gt;var threeTimes = makeRepeater(3);
608
+ var fourTimes = makeRepeater(4);
609
+ alert( threeTimes(&amp;#39;hi&amp;#39;) );
610
+ // =&amp;gt; &amp;#39;hi hi hi &amp;#39;
611
+ alert( fourTimes(&amp;#39;hi&amp;#39;) );
612
+ // =&amp;gt; &amp;#39;hi hi hi hi &amp;#39;&lt;/pre&gt;
613
+
614
+ &lt;p&gt;
615
+ Nothing spectacular, right? But look closely. The function returned by
616
+ &lt;code&gt;makeRepeater&lt;/code&gt; contains a reference to &lt;code&gt;times&lt;/code&gt;,
617
+ which is a local variable of &lt;code&gt;makeRepeater&lt;/code&gt;. When we call
618
+ &lt;code&gt;threeTimes&lt;/code&gt; or &lt;code&gt;fourTimes&lt;/code&gt; the
619
+ &lt;code&gt;makeRepeater&lt;/code&gt; call has already returned and &lt;code&gt;times&lt;/code&gt;
620
+ should be out of scope. Or should it?
621
+ &lt;/p&gt;
622
+
623
+ &lt;h3&gt;Extra life for your local scope&lt;/h3&gt;
624
+
625
+ &lt;p&gt;
626
+ You may try to argue and say that the &lt;code&gt;times&lt;/code&gt; inside
627
+ &lt;code&gt;threeTimes&lt;/code&gt; is not a &lt;i&gt;reference&lt;/i&gt; to the
628
+ &lt;code&gt;times&lt;/code&gt; from &lt;code&gt;makeRepeater&lt;/code&gt;, but just
629
+ a &lt;i&gt;copy&lt;/i&gt; of that value. Well, sadly I&amp;#39;ll have to prove you wrong. Let&amp;#39;s
630
+ modify our code just a little.
631
+ &lt;/p&gt;
632
+
633
+ &lt;pre name="code" class="js"&gt;var times;
634
+ function makeRepeater(){
635
+ return function(text){
636
+ var message = &amp;#39;&amp;#39;;
637
+ for (var i=0; i &amp;lt; times; i++) {
638
+ message += text + &amp;#39; &amp;#39;;
639
+ }
640
+ return message;
641
+ };
642
+ }
643
+
644
+ times = 3;
645
+ var threeTimes = makeRepeater();
646
+ times = 4;
647
+ var fourTimes = makeRepeater();
648
+ alert( threeTimes(&amp;#39;hi&amp;#39;) );
649
+ // =&amp;gt; &amp;#39;hi hi hi hi &amp;#39; ---&amp;gt; What?!?!
650
+ alert( fourTimes(&amp;#39;hi&amp;#39;) );
651
+ // =&amp;gt; &amp;#39;hi hi hi hi &amp;#39;&lt;/pre&gt;
652
+
653
+ &lt;p&gt;
654
+ If it&amp;#39;s not clear yet, let me write it down for you. The returned function
655
+ really keeps a reference to any outside values it will need when invoked.
656
+ In our original example, it kept a reference to the &lt;code&gt;times&lt;/code&gt;
657
+ local variable at the time it was produced. If we had created other
658
+ local variables inside &lt;code&gt;makeRepeater&lt;/code&gt; they would also become
659
+ available inside the returned function. In other words, all the scope
660
+ created during the call to &lt;code&gt;makeRepeater&lt;/code&gt; will be preserved
661
+ for the returned function. This happens when the returned (or inner)
662
+ function has a reference to anything defined in the parent (or outer)
663
+ function, i.e. the parent local scope. When this happens, we say that a
664
+ &lt;a href="http://en.wikipedia.org/wiki/Closure_(computer_science)"&gt;closure&lt;/a&gt;
665
+ has been created.
666
+ &lt;/p&gt;
667
+
668
+ &lt;h3&gt;Closures can be tricky&lt;/h3&gt;
669
+
670
+ &lt;p&gt;
671
+ It&amp;#39;s important to understand the mechanics of closures to avoid
672
+ subtle bugs in our code. Look at this piece of code, adapted from
673
+ a real bug I had to fix.
674
+ &lt;/p&gt;
675
+
676
+ &lt;pre name="code" class="js"&gt;&amp;lt;input type=&amp;quot;button&amp;quot; value=&amp;quot;Button 1&amp;quot; id=&amp;quot;btn1&amp;quot;&amp;gt;
677
+ &amp;lt;input type=&amp;quot;button&amp;quot; value=&amp;quot;Button 2&amp;quot; id=&amp;quot;btn2&amp;quot;&amp;gt;
678
+ &amp;lt;input type=&amp;quot;button&amp;quot; value=&amp;quot;Button 3&amp;quot; id=&amp;quot;btn3&amp;quot;&amp;gt;
679
+
680
+ &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
681
+ function createEventHandlers(){
682
+ var btn;
683
+ for(var i=1; i &amp;lt;= 3; i++){
684
+ btn = document.getElementById(&amp;#39;btn&amp;#39; + i);
685
+ btn.onclick = function(){
686
+ alert(&amp;#39;Clicked button #&amp;#39; + i);
687
+ }
688
+ }
689
+ }
690
+ createEventHandlers();
691
+ &amp;lt;/script&amp;gt;&lt;/pre&gt;
692
+
693
+ &lt;p&gt;
694
+ If you put this code in a page and click the three buttons you will see
695
+ that all of them will show the message &amp;quot;Clicked button #4&amp;quot;. Armed with
696
+ our understanding of closures we can immediately understand that this
697
+ bug is being caused by that reference to &lt;code&gt;i&lt;/code&gt; used inside
698
+ the event handler. We can fix that.
699
+ &lt;/p&gt;
700
+
701
+ &lt;pre name="code" class="js"&gt;function createEventHandlers(){
702
+ var btn;
703
+ for(var i=1; i &amp;lt;= 3; i++){
704
+ btn = document.getElementById(&amp;#39;btn&amp;#39; + i);
705
+ btn.onclick = createOneHandler(i);
706
+ }
707
+ }
708
+
709
+ function createOneHandler(number){
710
+ return function() {
711
+ alert(&amp;#39;Clicked button #&amp;#39; + number);
712
+ }
713
+ }&lt;/pre&gt;
714
+
715
+ &lt;p&gt;
716
+ The above code works because we are not creating functions inside
717
+ the &lt;code&gt;for&lt;/code&gt; loop, hence not producing closures on the same local scope.
718
+ There is a different set of closures being produced by
719
+ &lt;code&gt;createOneHandler&lt;/code&gt;, but those are not pointing to the same
720
+ parent scope. Each of these three new closures contain a different
721
+ scope, created by each call to &lt;code&gt;createOneHandler&lt;/code&gt;
722
+ &lt;/p&gt;
723
+
724
+ &lt;h3&gt;Closing thoughts&lt;/h3&gt;
725
+
726
+ &lt;p&gt;
727
+ Closures, of course, are not an exclusive feature of JavaScript. It&amp;#39;s
728
+ a very important trait of functional languages. Even in C#, when
729
+ we use lambdas, closures are created &amp;mdash; many times without us
730
+ noticing.
731
+ &lt;/p&gt;
732
+ &lt;p&gt;
733
+ The key to properly using closures in our code is to pay attention
734
+ to locally scoped values from the outer function being used in the
735
+ body of the inner function. Most of the times this will work as
736
+ intended by the developer but, when it doesn&amp;#39;t, stop and check
737
+ if more than one closure is sharing the same local scope or if
738
+ these local values are changing between the inner function
739
+ creation and its invocation.
740
+ &lt;/p&gt;
741
+
742
+ &lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=44499" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx">JavaScript-Demystified</category></item><item><title>JavaScript, 5 ways to call a function</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx</link><pubDate>Mon, 09 Feb 2009 06:03:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:44041</guid><dc:creator>sergiopereira</dc:creator><slash:comments>25</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/sergio_pereira/rsscomments.aspx?PostID=44041</wfw:commentRss><comments>http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx#comments</comments><description>&lt;div class="note"&gt;
743
+ This post is part of a series called &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx"&gt;JavaScript Demystified&lt;/a&gt;.
744
+ &lt;/div&gt;
745
+
746
+ &lt;p&gt;
747
+ Time after time I find JavaScript code that has bugs caused by lack of proper understanding of how functions work in JavaScript (a lot of that code has been written by me, by the way.) JavaScript has functional programming characteristics, and that can get in our way until we decide to face and learn it.
748
+ &lt;/p&gt;
749
+
750
+ &lt;p&gt;
751
+ For starters, let&amp;#39;s examine five ways to invoke a function. On the surface we might be tempted to think that functions work exactly like C#, but we will see that there are important differences and ignoring them will undoubtedly result in hard to track bugs.
752
+ &lt;/p&gt;
753
+
754
+ &lt;p&gt;
755
+ Let&amp;#39;s first create a simple function that we will be using through the rest of this post. This function will just return an array with the current value of &lt;code&gt;this&lt;/code&gt; and the two supplied arguments.
756
+ &lt;/p&gt;
757
+
758
+
759
+ &lt;pre name="code" class="js:nogutter"&gt;&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
760
+ function makeArray(arg1, arg2){
761
+ return [ this, arg1, arg2 ];
762
+ }
763
+ &amp;lt;/script&amp;gt;&lt;/pre&gt;
764
+
765
+ &lt;h3&gt;Most common way, unfortunately, global function calls&lt;/h3&gt;
766
+
767
+
768
+ &lt;p&gt;
769
+ When we are learning JavaScript we learn how to define functions using the syntax used in the example above. We learn that it&amp;#39;s also very easy to call that function &amp;mdash; all we need to do is:
770
+ &lt;/p&gt;
771
+
772
+
773
+ &lt;pre name="code" class="js:nogutter"&gt;makeArray(&amp;#39;one&amp;#39;, &amp;#39;two&amp;#39;);
774
+ // =&amp;gt; [ window, &amp;#39;one&amp;#39;, &amp;#39;two&amp;#39; ]&lt;/pre&gt;
775
+
776
+
777
+ &lt;p&gt;
778
+ Wait a minute. What&amp;#39;s that &lt;code&gt;window&lt;/code&gt; object doing there? Why is it the value of &lt;code&gt;this&lt;/code&gt;? If you haven&amp;#39;t stopped to think about it, please stay with me here.
779
+ &lt;/p&gt;
780
+
781
+ &lt;p&gt;
782
+ In JavaScript, and I&amp;#39;m not talking specifically about the browser here, there&amp;#39;s a default/global object. It&amp;#39;s as if every code that we write which seems to be just &amp;quot;loose&amp;quot; inside your script (i.e. outside of any object declaration) is actually being written in the context of that global object. In our case, that &lt;code&gt;makeArray&lt;/code&gt; function isn&amp;#39;t just a loose &amp;quot;global&amp;quot; function, it&amp;#39;s a method of the global object. Bringing ourselves back to the browser, the global object is mapped to the &lt;code&gt;window&lt;/code&gt; object in this environment. Let&amp;#39;s prove that.
783
+ &lt;/p&gt;
784
+
785
+
786
+ &lt;pre name="code" class="js:nogutter"&gt;alert( typeof window.methodThatDoesntExist );
787
+ // =&amp;gt; undefined
788
+ alert( typeof window.makeArray);
789
+ // =&amp;gt; function&lt;/pre&gt;
790
+
791
+
792
+ &lt;p&gt;
793
+ What all this means is that calling &lt;code&gt;makeArray&lt;/code&gt; like we did before is the same as calling as follows.
794
+ &lt;/p&gt;
795
+
796
+
797
+ &lt;pre name="code" class="js:nogutter"&gt;window.makeArray(&amp;#39;one&amp;#39;, &amp;#39;two&amp;#39;);
798
+ // =&amp;gt; [ window, &amp;#39;one&amp;#39;, &amp;#39;two&amp;#39; ]&lt;/pre&gt;
799
+
800
+
801
+ &lt;p&gt;
802
+ I say it&amp;#39;s unfortunate that this is the most common way because it leads us to declare our functions globally by default. And we all know that global members are not exactly the best practice in software programming. This is especially true in JavaScript. Avoid globals in JavaScript, you won&amp;#39;t regret it.
803
+ &lt;/p&gt;
804
+
805
+ &lt;div class="note"&gt;
806
+ &lt;span class="legend"&gt;&lt;b&gt;JavaScript function invocation rule #1&lt;/b&gt;&lt;/span&gt;
807
+ In a function called directly without an explicit owner object, like &lt;code&gt;myFunction()&lt;/code&gt;, causes the value of &lt;code&gt;this&lt;/code&gt; to be the default object (&lt;code&gt;window&lt;/code&gt; in the browser).
808
+ &lt;/div&gt;
809
+
810
+ &lt;h3&gt;Method call&lt;/h3&gt;
811
+
812
+ &lt;p&gt;
813
+ Let&amp;#39;s now create a small object and use the &lt;code&gt;makeArray&lt;/code&gt; function as one of its methods. We will declare the object using the literal notation. Let&amp;#39;s also call this method.
814
+ &lt;/p&gt;
815
+
816
+
817
+ &lt;pre name="code" class="js:nogutter"&gt;//creating the object
818
+ var arrayMaker = {
819
+ someProperty: &amp;#39;some value here&amp;#39;,
820
+ make: makeArray
821
+ };
822
+
823
+ //invoke the make() method
824
+ arrayMaker.make(&amp;#39;one&amp;#39;, &amp;#39;two&amp;#39;);
825
+ // =&amp;gt; [ arrayMaker, &amp;#39;one&amp;#39;, &amp;#39;two&amp;#39; ]
826
+ // alternative syntax, using square brackets
827
+ arrayMaker[&amp;#39;make&amp;#39;](&amp;#39;one&amp;#39;, &amp;#39;two&amp;#39;);
828
+ // =&amp;gt; [ arrayMaker, &amp;#39;one&amp;#39;, &amp;#39;two&amp;#39; ]&lt;/pre&gt;
829
+
830
+
831
+ &lt;p&gt;
832
+ See the difference here? The value of &lt;code&gt;this&lt;/code&gt; became the object itself. You may be wondering why isn&amp;#39;t it still &lt;code&gt;window&lt;/code&gt; since that&amp;#39;s how the original function had been defined. Well, that&amp;#39;s just the way functions are passed around in JavaScript. &lt;code&gt;Function&lt;/code&gt; is a standard data type in JavaScript, an object indeed; you can pass them around and copy them. It&amp;#39;s as if the entire function with argument list and body was copied and assigned to make in &lt;code&gt;arrayMaker&lt;/code&gt;. It&amp;#39;s just like defining &lt;code&gt;arrayMaker&lt;/code&gt; like this:
833
+ &lt;/p&gt;
834
+
835
+
836
+ &lt;pre name="code" class="js:nogutter"&gt;var arrayMaker = {
837
+ someProperty: &amp;#39;some value here&amp;#39;,
838
+ make: function (arg1, arg2) {
839
+ return [ this, arg1, arg2 ];
840
+ }
841
+ };&lt;/pre&gt;
842
+
843
+ &lt;div class="note"&gt;
844
+ &lt;span class="legend"&gt;&lt;b&gt;JavaScript function invocation rule #2&lt;/b&gt;&lt;/span&gt;
845
+ In a function called using the method invocation syntax, like &lt;code&gt;obj.myFunction()&lt;/code&gt; or &lt;code&gt;obj[&amp;#39;myFunction&amp;#39;]()&lt;/code&gt;, causes the value of &lt;code&gt;this&lt;/code&gt; to be &lt;code&gt;obj&lt;/code&gt;.
846
+ &lt;/div&gt;
847
+
848
+
849
+ &lt;p&gt;
850
+ This is a major source of bugs in event handling code. Look at these examples.
851
+ &lt;/p&gt;
852
+
853
+
854
+ &lt;pre name="code" class="js:nogutter"&gt;&amp;lt;input type=&amp;quot;button&amp;quot; value=&amp;quot;Button 1&amp;quot; id=&amp;quot;btn1&amp;quot; /&amp;gt;
855
+ &amp;lt;input type=&amp;quot;button&amp;quot; value=&amp;quot;Button 2&amp;quot; id=&amp;quot;btn2&amp;quot; /&amp;gt;
856
+ &amp;lt;input type=&amp;quot;button&amp;quot; value=&amp;quot;Button 3&amp;quot; id=&amp;quot;btn3&amp;quot; onclick=&amp;quot;buttonClicked();&amp;quot;/&amp;gt;
857
+
858
+ &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
859
+ function buttonClicked(){
860
+ var text = (this === window) ? &amp;#39;window&amp;#39; : this.id;
861
+ alert( text );
862
+ }
863
+ var button1 = document.getElementById(&amp;#39;btn1&amp;#39;);
864
+ var button2 = document.getElementById(&amp;#39;btn2&amp;#39;);
865
+
866
+ button1.onclick = buttonClicked;
867
+ button2.onclick = function(){ buttonClicked(); };
868
+ &amp;lt;/script&amp;gt;&lt;/pre&gt;
869
+
870
+
871
+ &lt;p&gt;
872
+ Clicking the first button will display &lt;i&gt;&amp;quot;btn1&amp;quot;&lt;/i&gt; because it&amp;#39;s a method invocation and &lt;code&gt;this&lt;/code&gt; will be assigned the owner object (the button input element.) Clicking the second button will display &lt;i&gt;&amp;quot;window&amp;quot;&lt;/i&gt; because &lt;code&gt;buttonClicked&lt;/code&gt; is being called directly (i.e. not like &lt;code&gt;obj.buttonClicked()&lt;/code&gt;.) This is the same thing that happens when we assign the event handler directly in the element&amp;#39;s tag, as we have done for the third button. Clicking the third button does the same of the second button.
873
+ &lt;/p&gt;
874
+
875
+ &lt;p&gt;
876
+ That&amp;#39;s another advantage of using a library like jQuery. When defining event handlers in jQuery, the library will take care of overriding the value of &lt;code&gt;this&lt;/code&gt; and make sure it contains a reference to the element that was the source of the event.
877
+ &lt;/p&gt;
878
+
879
+ &lt;pre name="code" class="js:nogutter"&gt;//using jQuery
880
+ $(&amp;#39;#btn1&amp;#39;).click( function() {
881
+ alert( this.id ); // jQuery ensures &amp;#39;this&amp;#39; will be the button
882
+ });&lt;/pre&gt;
883
+
884
+ &lt;p&gt;
885
+ How does jQuery override the value of &lt;code&gt;this&lt;/code&gt;? Keep reading.
886
+ &lt;/p&gt;
887
+
888
+ &lt;h3&gt;Two more: &lt;code&gt;apply()&lt;/code&gt; and &lt;code&gt;call()&lt;/code&gt;&lt;/h3&gt;
889
+
890
+ &lt;p&gt;
891
+ The more you leverage functions in JavaScript, the more you find yourself passing functions around and needing to invoke them in different contexts. Just like jQuery does in the event handler functions, you&amp;#39;ll often need to override the value of &lt;code&gt;this&lt;/code&gt;. Remember I told you functions are objects in JavaScript? Functions have predefined methods, two of them are &lt;code&gt;apply()&lt;/code&gt; and &lt;code&gt;call()&lt;/code&gt;. We can use them to do precisely that kind of overriding.
892
+ &lt;/p&gt;
893
+
894
+ &lt;pre name="code" class="js:nogutter"&gt;var gasGuzzler = { year: 2008, model: &amp;#39;Dodge Bailout&amp;#39; };
895
+ makeArray.apply( gasGuzzler, [ &amp;#39;one&amp;#39;, &amp;#39;two&amp;#39; ] );
896
+ // =&amp;gt; [ gasGuzzler, &amp;#39;one&amp;#39; , &amp;#39;two&amp;#39; ]
897
+ makeArray.call( gasGuzzler, &amp;#39;one&amp;#39;, &amp;#39;two&amp;#39; );
898
+ // =&amp;gt; [ gasGuzzler, &amp;#39;one&amp;#39; , &amp;#39;two&amp;#39; ]&lt;/pre&gt;
899
+
900
+
901
+ &lt;p&gt;
902
+ The two methods are similar. The first parameter will override &lt;code&gt;this&lt;/code&gt;. They differ on the subsequent arguments. &lt;code&gt;Function.apply()&lt;/code&gt; takes an array of values that will be passed as arguments to the function and &lt;code&gt;Function.call()&lt;/code&gt; takes the same arguments separately. In practice I believe you&amp;#39;ll find that &lt;code&gt;apply()&lt;/code&gt; is more convenient in most cases.
903
+ &lt;/p&gt;
904
+
905
+ &lt;div class="note"&gt;
906
+ &lt;span class="legend"&gt;&lt;b&gt;JavaScript function invocation rule #3&lt;/b&gt;&lt;/span&gt;
907
+ If we want to override the value of &lt;code&gt;this&lt;/code&gt; without copying the function to another object, we can use &lt;code&gt;myFunction.apply( obj )&lt;/code&gt; or &lt;code&gt;myFunction.call( obj )&lt;/code&gt;.
908
+ &lt;/div&gt;
909
+
910
+ &lt;h3&gt;Constructors&lt;/h3&gt;
911
+
912
+ &lt;p&gt;
913
+ I won&amp;#39;t delve into the details of defining types in JavaScript but at minimum we should be aware that there aren&amp;#39;t classes in JavaScript and that any custom type needs a constructor function. It&amp;#39;s also a good idea to define the methods of your type using the &lt;code&gt;prototype&lt;/code&gt; object, which is a property of the constructor function. Let&amp;#39;s create a small type.
914
+ &lt;/p&gt;
915
+
916
+
917
+ &lt;pre name="code" class="js:nogutter"&gt;//declaring the constructor
918
+ function ArrayMaker(arg1, arg2) {
919
+ this.someProperty = &amp;#39;whatever&amp;#39;;
920
+ this.theArray = [ this, arg1, arg2 ];
921
+ }
922
+ // declaring instance methods
923
+ ArrayMaker.prototype = {
924
+ someMethod: function () {
925
+ alert( &amp;#39;someMethod called&amp;#39;);
926
+ },
927
+ getArray: function () {
928
+ return this.theArray;
929
+ }
930
+ };
931
+
932
+ var am = new ArrayMaker( &amp;#39;one&amp;#39;, &amp;#39;two&amp;#39; );
933
+ var other = new ArrayMaker( &amp;#39;first&amp;#39;, &amp;#39;second&amp;#39; );
934
+
935
+ am.getArray();
936
+ // =&amp;gt; [ am, &amp;#39;one&amp;#39; , &amp;#39;two&amp;#39; ]&lt;/pre&gt;
937
+
938
+
939
+ &lt;p&gt;
940
+ What&amp;#39;s very important to note here is the presence of the &lt;code&gt;new&lt;/code&gt; operator before the function call. Without that your function will just be called like a global function and those properties that we are creating would be created on the global object (&lt;code&gt;window&lt;/code&gt;.) And you don&amp;#39;t want to do that. Another issue is that, because you typically don&amp;#39;t have an explicit return value in your constructor function, you&amp;#39;ll end up assigning &lt;code&gt;undefined&lt;/code&gt; to some variable if you forget to use &lt;code&gt;new&lt;/code&gt;. For these reasons it&amp;#39;s a good convention to name your constructor functions starting with an upper case character. This should serve as a reminder to put the &lt;code&gt;new&lt;/code&gt; operator before the call.
941
+ &lt;/p&gt;
942
+
943
+ &lt;p&gt;
944
+ With that taken care of, the code inside the constructor is very similar to any constructor you probably have written in other languages. The value of &lt;code&gt;this&lt;/code&gt; will be the new object that you are trying to initialize.
945
+ &lt;/p&gt;
946
+
947
+ &lt;div class="note"&gt;
948
+ &lt;span class="legend"&gt;&lt;b&gt;JavaScript function invocation rule #4&lt;/b&gt;&lt;/span&gt;
949
+ When used as a constructor, like &lt;code&gt;new MyFunction()&lt;/code&gt;, the value of &lt;code&gt;this&lt;/code&gt; will be a brand new object provided by the JavaScript runtime. If we don&amp;#39;t explictly return anything from that function, &lt;code&gt;this&lt;/code&gt; will be considered its return value.
950
+ &lt;/div&gt;
951
+
952
+ &lt;h3&gt;It&amp;#39;s a wrap&lt;/h3&gt;
953
+
954
+ &lt;p&gt;
955
+ I hope understanding the differences between the invocation styles help you keeping bugs out of your JavaScript code. Some of these bugs can be very tricky do identify and making sure you always know what the value of &lt;code&gt;this&lt;/code&gt; will be is a good start to avoiding them in the first place.
956
+ &lt;/p&gt;
957
+
958
+
959
+ &lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=44041" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx">JavaScript-Demystified</category></item></channel></rss>