This repository has been archived by the owner on Nov 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstructors.html
317 lines (303 loc) · 19.3 KB
/
constructors.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<!DOCTYPE html>
<html>
<head>
<title>Constructors at Work</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=BioRhyme:800" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans:400,400i,700,700i,800" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=IBM+Plex+Mono:300,400,400i,700" rel="stylesheet">
<link rel='stylesheet' type='text/css' href="../css/reset.css">
<link rel='stylesheet' type='text/css' href="../css/prism.css">
<link rel='stylesheet' type='text/css' href="../css/styles.css">
</head>
<body>
<header>
<pre id='ascii-title' style='font-size:2vw; line-height:0.80em; letter-spacing: -0.35em; font-weight:800;'>
______ ____
| | .'. |`````````, |``````. | | .'. `````|````` `````````:' .~ ~. |.. | | .'`,
|_________| .''```. |'''|''''' | | |_________| .''```. | ..' | | | ``.. | |______ `'
| | .' `. | `. | | | | .' `. | ..'' | | | ``.. | | .'`,
| | .' `. | `. |......' | | .' `. | .:,,,,,,,,, `.______.' | ``| |___________ `'
______ ______ ______ ______
.~ ~. .~ ~. |.. | ..''.. `````|````` |`````````, | | .~ ~. `````|````` .~ ~. |`````````, ..''..
| | | | ``.. | .'' | |'''|''''' | | | | | | |'''|''''' .''
| | | | ``.. | ..' | | `. | | | | | | | `. ..'
`.______.' `.______.' | ``| ''..'' | | `. `._______.' `.______.' | `.______.' | `. ''..''
______
.'. `````|````` `. .' .~ ~. |`````````, | ..''
.''```. | `. .' | | |'''|''''' |..''
.' `. | `. . .' | | | `. |``..
.' `. | `.' `.' `.______.' | `. | ``..
</pre>
<h2 class='date'> August 6th, 2018</h2>
</header>
<article class='container'>
<section id="todo">
<h1>To Do's:</h1>
<ul>
<li>Administrivia</li>
<li>Practice With Objects</li>
<li>Intro to Constructors</li>
<li>Building On Constructors</li>
</ul>
</section>
<section>
<h1>Administrivia</h1>
<p>Hello, everyone, and welcome to another new unit! We'll be putting the brakes on NPM for now, working in Node to
master your understanding of JavaScript objects. During today's class, we'll be focusing on making your knowledge of objects
much more robust such that you can use them creatively and efficiently.</p>
</section>
<section>
<h1>Practice With Objects</h1>
<p>Objects are powerful, flexible, and beautifully efficient data structures capable of extensive functionality while offering
the ability to minimize repeated code, much like functions. They are the crux of modern JavaScript development: structures with self-contained
bundles of functions and data that stay succinct and organized. In Node, the special object
<code>module.exports</code> allows us to use prewritten code. Let's focus just on the objects themselves for now.
</p>
<h2>Syntax Refresher</h2>
<p>Recall that objects can have any data type as a child element, stored as a key-value pair—ints,
floats, strings, arrays, functions, other objects, etc. Here's a quick reminder
of what that might look like with multiple different types:
</p>
<pre><code class="language-JavaScript">// Assuming we installed Moment.js
const moment = require("moment");
var person = {
name: "Dr. Thaddeus Venture",
birthday: new moment("4/30/1960","MM/DD/YYYY"),
occupation: "Super scientist",
family: ["Hank Venture", "Dean Venture"],
getAge: function(){
return moment().diff(this.birthday, "years");
}
};
// Output current age based on stored birthday
console.log(person.getAge());</code></pre>
<p>Let's do a quick activity to refresh your skills with creating objects.
<div class="student-activity">
<h2>Student activity!</h2>
<h3>Raining Cats and Dogs</h3>
<p>Make a dogs object with three keys:</p>
<ul>
<li>First key called "raining" with a value of <code>true</code></li>
<li>Second key called "noise" with a value of "Woof!"</li>
<li>Third key called "makeNoise" which contains a function which logs the noise to the screen if it is raining dogs</li>
</ul>
<p>Then, make a cats object with three keys:</p>
<ul>
<li>First key called "raining" with a value of <code>false</code></li>
<li>Second key called "noise" with a value of "Meow!"</li>
<li>Third key called "makeNoise" which contains a function which logs the noise to the screen if it is raining cats</li>
</ul>
<p>Make the dog bark, and make the cat meow.</p>
<p><span class="bonus">Bonus:</span> Create a function called "massHysteria" which takes in both the cats and the dogs object and prints <span class="italic mid-accent">"DOGS AND CATS LIVING
TOGETHER! MASS HYSTERIA!"</span> if both of the <code>raining</code> keys are equal to true.</p>
<p>The focus of this activity is to maintain as much simplicity as possible. After building the required objects, refactor your
code until it is as simple as you can make it.
</p>
</div>
<div class="review">
<h2>Raining Cats and Dogs Live-coding</h2>
<p>Let's get a couple of people to code out different parts of the assignment, explaining
logic along the way.
</p>
<p>As we complete the code, do you see anything that seems redundant?
Are there foolproof ways to get rid of this redundancy?
</p>
</div>
</section>
<section>
<h1>Intro to Constructors</h1>
<p>An easy way to think about a <span class="note">constructor</span> is a template function that creates
objects with a particular layout. Instead of what we saw earlier with identically-structured
objects, we can create a constructor that literally <span class="italic">constructs</span>
an object in that format. Let's reduce the redundancy in that previous example after going
over the basic syntax.</p>
<pre><code class="language-javascript">// Common convention is to capitalize
// Constructors--plus camelCase, do CamelCase.
// This helps us distinguish functions from Constructors
function TestObj(a, b){
// use "this" to set the object's own parameters to the given arguments
this.a = a;
this.b = b;
this.c = "foo"; // default value for all returned objects
}
var foo = new TestObj("42","ham"),
bar = new TestObj("23","spam"),
baz = new TestObj("4533","eggs");
console.log(foo.a === bar.a); // false
console.log(bar.c === baz.c); // true
</code></pre>
<p>To make something abundantly clear: <span class="mid-accent bold">never,
<span class="italic">ever</span> call the constructor function on its own.</span> It
will override all the variables of every instance of the object "template" by bringing
those variables into the global scope. Remember what <code>this</code> refers to outside of functions:
the window in the browser, and on the back-end a set of Node globals including the process and console.</p>
<p>Now that we've gotten that out of the way, let's go over using a constructor with the <code>person</code> object we saw earlier.
<pre><code class="language-javascript">// Define a new constructor for a Person object
function Person(name, birthday, occupation, family){
this.name = name;
this.birthday = new moment(birthday, "MM/DD/YYYY");
this.occupation = occupation;
this.family = family;
this.getAge = function(){
return moment().diff(this.birthday, "years");
}
}
var doc = new Person(
"Dr. Thaddeus Venture",
"4/30/1960",
"Super scientist",
["Hank Venture", "Dean Venture"]);
</code></pre>
<p>This code doesn't look particularly exciting, but it's demonstrably more efficient when we want multiple
objects with the same structure. If I wanted to add a new <code>Person</code> like in the code above,
what would I do without a constructor? It would be extremely redundant, even more so if I wanted to add more.
That, or I'd have to use prototypes. More on that later.
</p>
<p>Let's look at an updated "Raining Cats and Dogs" version.</p>
<div class="activity">
<h2>Instructor activity...</h2>
<p>We already know the basic functionality, so let's just go through the code
and see what changed. The resulting code should be visibly more concise.
</p>
</div>
<h2>Questions, comments before you dive into a new activity?</h2>
<hr>
<div class="student-activity">
<h2>Student activity!</h2>
<h3>Character Creation</h3>
<p>Over the course of this activity you are going to be using constructors to create simplistic
characters for use within a very basic Roleplaying Game (RPG).</p>
<p>Creativity is highly encouraged here—go
above and beyond and this activity will be a blast! Also feel free to modify any of the below properties, so long
as there are strings, numbers and at least one function in your constructor. Consider adding a second
constructor for attacks and/or spells, then keeping an array of moves a character can make.</p>
<p>At the very least, each character created using your constructor should have something like the following:</p>
<ul>
<li><span class="note">Name:</span> The character's name <span class="mid-accent">⟶</span> String</li>
<li><span class="note">Profession:</span> What the character does for a living <span class="mid-accent">⟶</span> String</li>
<li><span class="note">Gender:</span> The character's gender <span class="mid-accent">⟶</span> String</li>
<li><span class="note">Age:</span> The character's age <span class="mid-accent">⟶</span> Integer</li>
<li><span class="note">Strength:</span> Abstraction for how strong the character is <span class="mid-accent">⟶</span> Integer</li>
<li><span class="note">HitPoints (HP):</span> abstraction for how much health the character has <span class="mid-accent">⟶</span> Integer</li>
<li><span class="note">PrintStats:</span> Function which prints all of a character's properties to the screen</li>
</ul>
<p>Once you have created your constructor, create two new characters and print their properties to the screen.</p>
<p>Fool around and get comfortable with your constructor before moving onto the next parts of the activity.</p>
Once comfortable with your constructor, it is time to start making this character creation system a little
more reactive by adding in some more methods:
<ul>
<li><span class="note">IsAlive</span> Function which prints whether or not this character is alive by looking into their hitpoints and determining whether they
are above or below zero.</li>
<li><span class="note">Attack</span> Function which takes in a second character's hitpoints and subtracts this character's strength from it.</li>
<li><span class="note">LevelUp</span> Function which increases this character's Age by 1, their Strength by 5, and their HitPoints by 25.</li>
</ul>
<p><span class="bonus">Bonus:</span> After completing the previous sections and making sure they work, you now have everything you need to create a very basic
RPG where two characters fight one another. Don't worry if you cannot finish this part of the activity as, by completing
the above sections you are well on your way to mastering constructors!</p>
</div>
<div class="review">
<h2>Character Creation Review</h2>
<p>Let's go over the code line-by-line, then tackle the bonus version.</p>
</div>
</section>
<div class="page-break">
<h1>Break Time!</h1>
</div>
<section>
<h1>Building On Constructors</h1>
<p>One of the best parts about constructed objects is the ability to mutate their contents
whenever it becomes advantageous to do so. How would we go about adding new and unique properties and
methods to constructed objects? In what situation would we want to do this?
</p>
<p>Perhaps we would like our constructed objects to differ in some way. Perhaps we would like to make a
"Person" constructor that returns an object with a name and occupation. If we were to make
"Student" and "Instructor" constructors, we wouldn't be able to leverage the already existing code.
However, if we <span class="italic">did</span> use the constructor alone, an instructor may end up with
an assignments sub-object, and students a lesson plan sub-object.
</p>
<pre><code class="language-javascript">function Person(name, occupation, color){
this.name = name;
this.occupation = occupation;
this.favoriteColor = color;
}
var instructor = new Person("Alice", "instructor", "lavender"),
student = new Person("Bob", "student", "chartreuse");
student.homework = {
node: {
due: "8/11/18",
finished: false
}
};
instructor.lessonPlans = {
constructors: {
date: "8/6/18",
url: "zatchheems.github.io/11-js-constructors/html/constructors.html"
}
}</code></pre>
<h4>Any questions before we continue?</h4>
<hr>
<div class="student-activity">
<h2>Student activity!</h2>
<h3>Tamagotchi Time: Part I</h3>
<p>Remember Tamagotchis? They were those little toys that contained "digital pets" which you could feed, pet, play with, and
care for. Kind of like Furbies but a whole lot less terrifying. Over the next thirty minutes or so, you are going to create
your own basic Tamagotchi clone using constructors.</p>
<p>Create a constructor called "DigitalPal" (or something similar)
which will create four properties and four methods:</p>
<h4>Properties:</h4>
<ol>
<li>The first property is <span class="monospace accent">hungry</span> and it initially starts out as false</li>
<li>The second property is <span class="monospace accent">sleepy</span> and it initially starts out as false</li>
<li>The third property is <span class="monospace accent">bored</span> and it initially starts out as true</li>
<li>The fourth property is <span class="monospace accent">age</span> and it initially starts out at 0</li>
</ol>
<h4>Methods:</h4>
<ol>
<li>The first method is <code>feed()</code> — If hungry is true, print "That was yummy!", set hungry to false, and then set sleepy to true.
If hungry is false, print "No thanks! I'm full."</li>
<li>The second method is <code>sleep()</code> — If sleepy is true, print "Zzzzzzzz", set sleepy to false, then set bored to true, and then
run increaseAge(). If sleepy is false, print "No way! I'm not tired."</li>
<li>The third method is <code>play()</code> — If bored is true, print "Yay! Let's play!", set bored to false, and then set hungry to true.
If bored is false, print "Not right now. Later?"</li>
<li>The fourth method is <code>increaseAge()</code> — This method runs within the <code>sleep()</code> method when the DigitalPal goes to sleep and
increases the DigitalPal's age by one while also printing <code class="language-JavaScript">`Happy Birthday to me! I am ${age} years old!`</code></li>
</ol>
<h3>Part II:</h3>
<p>Create a variable named "Dog" that is set to a new DigitalPal before adding the following unique properties/methods to it:</p>
<ul>
<li><span class="monospace accent">Outside</span> — Initially set to false</li>
<li><code>Bark()</code> — Prints out "Woof! Woof!" when run</li>
<li><code>goOutside()</code> — If outside is false, prints "Yay! I love the outdoors!", sets outside to true, and runs Bark(). If outside is true, prints
"We're already outside though..."</li>
<li><code>goInside()</code> — If outside is true, prints "Do we have to? Fine..." and sets outside to false. If outside is false, prints "I'm already inside..."</li>
</ul>
<p>Make a second variable named "Cat" that is set to a new DigitalPal and add the following methods to it:</p>
<ul>
<li><span class="monospace accent">HouseCondition</span> — Initially set to 100, but not for long...</li>
<li><code>meow()</code> — prints out "Meow! Meow!" when run</li>
<li><code>destroyFurniture()</code> — Lowers HouseCondition by 10 and prints `MUAHAHAHAHA! TAKE THAT FURNITURE!` to the screen. Also sets bored to false and sleepy
to true. If HouseCondition is equal to 0, then this should not run anymore.</li>
<li><code>buyNewFurniture()</code> — Raises HouseCondition by 50 and prints "Are you sure about that?" to the screen.</li>
</ul>
<p>Play around with your newly created digital pets for a bit and see what else you could add in order to make them even more
exciting!</p>
<p><span class="bonus">Bonus:</span> Make it so your Tamagotchis run off of user-input. It may sound easy at first, but this can actually be quite challenging.
We will be going over this in more detail during the next class.</p>
</div>
<div class="review">
<h2>Tamagotchi Review</h2>
<p>This activity has a lot of moving parts, so let's tackle the solution in sections by breaking it down
by method.
</p>
</div>
</section>
<div class="page-break">
<h1>That's all for today, see you Wednesday!</h1>
</div>
</article>
</body>
<!-- Script to make code pretty -->
<script type='text/javascript' src="../js/prism.js"></script>
</html>