Sunteți pe pagina 1din 29

JavaScript for Assholes

2012 Thomas S. Bradford


This version was published on 2012-08-15
This is a Leanpub book, for sale at:
http://leanpub.com/javascriptforassholes
Leanpub helps authors to self-publish in-progress ebooks.
We call this idea Lean Publishing. To learn more about
Lean Publishing, go to: http://leanpub.com/manifesto
To learn more about Leanpub, go to: http://leanpub.com
Tweet This Book!
Please help Thomas S. Bradford by spreading the word
about this book on Twitter!
The suggested hashtag for this book is #js4assholes.
Find out what other people are saying about the book by
clicking on this link to search for this hashtag on Twitter:
https://twitter.com/search/#js4assholes
Contents
Warning 1
Who is This Book For? . . . . . . . . . . . . . . 1
Why Am I Writing This Book? . . . . . . . . . 3
To Readers . . . . . . . . . . . . . . . . . . . . 4
To Reviewers . . . . . . . . . . . . . . . . . . . 5
Chapter One - JavaScript Goes Forth! 6
Computer Programming . . . . . . . . . . . . . 6
What Do I Need To Do First? . . . . . . . . . . 11
Your First Shitty Program . . . . . . . . . . . . 16
Data, Hes An Android, Right? . . . . . . . . . . 20
Warning
Throughout this text, I will be vulgar and somewhat insult-
ing. I will also speak in the first person and share far more
personal information with you than can be considered
appropriate. If you cant stomach that, then kindly fuck
off.
No, seriously, fuck off.
Who is This Book For?
Despite its title, its actually not for Assholes.
Im about to date myself, but I started programming in
around 1984, long before the commercial Internet and back
when the only way to obtain programming knowledge
without college was to join user groups where you ex-
changed 5.25 inch floppies with one another. Sure, you
could subscribe to Dr. Dobbs, but who had the cash for
that? I was 12 years old, and I had to ask my mother for
arcade money.
But regardless of our new-found immediate access to knowl-
edge, what was true then is true now there are two kinds
of programmers. There are the ones who feel a camaraderie
with their peers and those who feel a rivalry. Unfortu-
nately, despite the free software movements professed
stance on sharing, it seems as though those guys quite often
fall into the rivalry camp.
1
Warning 2
Curious where Im going with this? Okay, many of these
free software guys are complete fucking pricks who treat
newbies as if theyre some sort of diseased pieces of
shit, and theyre particularly brutal if those newbies show
even the slightest indication of coming from a world about
which the expert prick isnt dogmatic.
For example, a newbie user once proposed a patch to
a very popular Python open source project. The patch
addressed a major flaw in that projects wire protocol.
The author, instead of thanking the user for the patch and
accepting it humbly, attempted to humiliate the user by
pointing out the fact that his coding style seemed very
influenced by Java.
Hey, Douchbag! Your software was broken! This guy, even
if hes new to Python, was smart enough to identify and
correct your blunder! Instead of trying to humiliate him,
you should be kissing his ass and asking him to contribute
to your project. Id rather your software work than fit some
purists concept of what Python code should look like. You
fuckin dick!
And this is not an isolated incident. I see it all the time, and
it seems to be getting worse. Why should newbies feel
as if they have to apologize for seeking knowledge? Why
should they be told Well, a quick Google search would
tell you when you could just help them? I find it ironic
and utterly fucking shameful that the same people who
tout the virtues of Pair Programming are so quick to deny
someone the type of knowledge sharing that comes with
Warning 3
human interaction.
Ive always felt a camaraderie with those downtrodden
newbies, possibly because the same sort of dickish treat-
ment was bestowed upon me when I was young. When I
was about 13 or 14, I phoned a very famous UNIX guy to
ask about his file transfer protocols SDK. It cost $80, but I
couldnt afford that, so I ask him if hed share it with me,
to which his only repeated and socially-retarded reply was
Eighty Dollars!
Eighty Dollars, regardless of my pleas, over and over
again, and then, as my teenage voice finally cracked and
I had no choice but to admit defeat, he hung up the phone
on me. Ive had a bad taste in my mouth since then, and
the shitty behavior of many programmers hasnt assisted
in combating that.
So who is this book for? Its for you, kind and gentle
newbie. Im trying to save you the trouble of having to
ask some prick for help on the Internet only to be treated
like a fucking leper in the process. And heres a promise:
If I dont answer your questions in the book, ask me in real
life and I can guarantee you that I wont treat you like shit
After all, I was once you.
Why Am I Writing This Book?
I was sick of being bored to death by computer books, so I
set out to write one in my own voice, and as my own voice
Warning 4
is one from Boston, Massachusetts, its laced with profanity
and a glaring lack of political correctness. I dont feel as
if a computer book has to read like a college text, and I
also dont think that learning needs to be such a serious
endeavor.
My goal is to drag your ass quickly from the very basics
of computer programming to complete proficiency that
is, inasmuch as anyone can actually be proficient. Along
the way, I will mislead you, insult you, and probably make
you laugh your ass off unless youre an uptight prick, in
which case you shouldnt be reading this book anyway. In
the process, Im hoping youll accidentally learn a thing or
two.
To Readers
For the most part, Im going to assume that you have
absolutely no programming knowledge whatsoever. One
mistake I see many authors make is that they rush in
with their cocks out, foolishly assuming that their audience
knows even the first thing about software development, so
except for this Introductory Rant, dont worry about feeling
lost as youre reading the book.
I will also avoid talking about HTML and CSS for as long as
possible. This is a JavaScript book, not an HTML book. Ill
discuss HTML only insomuch as it supports the JavaScript
skills that are being presented (e.g. DOM Manipulation
bleh! ). Otherwise, I have no interest in overloading you
Warning 5
with presentation layer bullshit, especially if your hope is
to avoid HTML and CSS in your day to day work.
If youve downloaded this book from Leanpub.com, then
you hopefully know that its a work in progress, and that it
will be in a draft state for quite some time. So Id prefer that
you not complain about how short the book is or how its
missing chapters. My goal is to write a chapter per week
until the books completion, but as sometimes life gets in
the way, this may not always be possible.
To Reviewers
Ive published on Leanpub.com so that I can elicit early
feedback for the book and its direction. For the moment
Im more concerned with whether or not you feel the book
is engaging and whether or not youre actually learning the
material.
I dont care about formatting concerns, about spelling or
grammatical errors, and I certainly dont want to hear you
tell me that the material is profane or somehow offends
your gentle sensibilities. You read the warning, and so if
you have a problem with my approach, then you should
have already fucked off.
Chapter One - JavaScript
Goes Forth!
This chapter is a high level introduction to JavaScript. Well
quickly survey the landscape and some of the key topics,
but wont get into very much depth as that will be the
purpose of later chapters.
But before going forward, we should probably get some of
the basics out of the way. Youre either here because you
dont know shit about computer programming, or youre
coming from another programming language like Java
in which case, you probably also dont know shit about
computer programming.
So lets learn some shit.
Computer Programming
Much like the cast of Jersey Shore, computers are stupid
empty vessels that dont know how to do anything useful
on their own. They only do what theyre told, right or
wrong, and so the art of computer programming is learning
how to avoid telling computers to do the wrong things.
I say the wrong things because most of the time you
wont be telling a computer the right things, and thats okay
because you cant break your computer with JavaScript
6
Chapter One - JavaScript Goes Forth! 7
At least I dont think you can, but who knows, stranger
things have happened.
So dont approach computer programming as if it must
be done using an overly-structured methodology that is
supposed to consistently produce perfect results, because
it wont, it cant, and it shouldnt. The empirical method of
trial and error is essential to becoming a good programmer.
Youre gonna fuck up, probably a lot, and thats a good
thing.
So are you ready to fuck up? Good! Ill help you!
Computer Programs
Computer programs consist of instructions for the com-
puter to perform on your behalf. These instructions may
be as simple as displaying Hello, World! on the screen or
as complex as auto-piloting an airplane. What separates
a good program from a bad program is whether or not
the airplane avoids flying into the ocean Unless that was
your intent.
In modern nerd jargon, we call computer programs (or their
instructions) by the name of code and the act of creating
said code is referred to as coding. To take things to geek
extremes, computer programmers are often called coders.
Arent we fuckin clever? Yes, we are! Embarrassingly so!
Chapter One - JavaScript Goes Forth! 8
Programming Languages
Just like in the real world, where we need to communi-
cate with one another using some sort of understandable
language, so too do nerds have to talk to their computers.
Occasionally they speak to their computers out loud and in
vain, hoping that the computer will understand their woes,
but more often than not, they resort to typing instructions.
And like the real world where there are many languages,
German being the one I refuse to speak, computer program-
ming is performed using many programming languages.
There are reasons why so many exist, some are practical,
for example there are languages specifically for storing
information and some for presenting information. While
others are purely stylistic, for example Ruby and Python
do almost exactly the same things, but nerds are religious
in their adoration for one or the other.
Personally, I think Python sucks, especially for beginners,
but Imespousing the virtues of JavaScript at the same time,
so what the fuck does that say about me?
Compilation or Interpretation?
Depending on the programming language youre writing
in, sometimes your code needs to be translated before it
can perform its intended task. This translation is called
compilation and it is the process of taking your shitty
code and converting it into the indecipherable garbage
Chapter One - JavaScript Goes Forth! 9
that the computer will use to crash your operating system
repeatedly.
Some examples of compiled languages include C++ and
Java. Fortunately for you though, were learning JavaScript,
and JavaScript doesnt need to be compiled, so lets move
on.
In the case of a language that is not compiled, we instead
say that it is interpreted. This basically means that you
give your code to another program and that program tries
to figure out what to do with it. When it comes to
JavaScript, your code is usually going to be run by a Web
Browser, and thats good because it means the person who
youll subject to your masterpiece already has what they
need to use it.
Writing Programs for the Internet
When it comes to the Internet, we talk about its two
sides. These are the Client Side which is what the
user sees in his or her Web Browser, and the Server
Side which are programs running on somebody elses
computers. Server Side programs are the ones doing all the
hard work and consuming massive amounts of electricity,
while plunging the earth into a rapid downward spiral of
non-sustainability. But thats not your problem, is it?
Chapter One - JavaScript Goes Forth! 10
The Client Side - There be Monsters here
So far Ive set you up for failure because Im telling you that
youll be writing code and running it in a Web Browser.
What this means is that youll inevitably run into at least
one (or hundreds) of the browser incompatibilities that
exist, and trust me, there are a shitload of them.
It used to be that people blamed Microsoft for these incon-
sistencies, and rightfully so because the company had a ten-
dency to implement things in their own way. This created
a massive minefield that one has to deal with, because not
only is Internet Explorer incompatible with other browsers,
but its also incompatible with itself between versions.
Another source of pain is that Windows users either dont
know how or are not allowed to upgrade to the latest
version of Internet Explorer, meaning there are still web
sites out there that need to support versions of IE that were
first released on Windows 98.
But more recently, new culprits have entered the scene.
Microsoft is no longer the diabolical bully on the block
trying to dominate and monopolize the market. These days
that honor is shared by both Google and Apple. Im sure
Ill complain more about them later, but for now we should
get back to programming talk.
The Server Side - A Land of Milk and Honey
Dont be disheartened by all of this Web Browser shit
though, because well also be discussing JavaScript on the
Chapter One - JavaScript Goes Forth! 11
Server Side, which can be a rather enjoyable experience.
Granted, it wont be quite as enjoyable as those things
normal humans consider enjoyable, but youre a nerd, so
normal doesnt apply to you, does it?
The good thing about the Server Side is that you con-
trol it, so you dont have to deal with the overwhelming
volatility that targeting a Web Browser presents. Tradi-
tionally, Server Side development has been done in lan-
guages like Java, Python or Ruby, but recently a platform
called Node.js has been gaining incredible popularity, and
deservedly so because its pretty fuckin awesome.
Fortunately for you, Node.js is a JavaScript platform, mean-
ing youll be learning skills that can be used on both the
Client and the Server Sides. I will also be dedicating a good
percentage of this book to Node.js, so keep your pants on
if you think the Client Side is for suckers, because well be
kicking Server ass as well!
What Do I Need To Do First?
Well, if you have a Web Browser, then you already have
part of what you need to get started, and I think most
operating systems come with at least one of those. On
Windows, youll have Internet Explorer, though I suggest
Firefox or Chrome since IE is, wellIE, and it sucks. On the
Mac, youll have Safari, which also sucks in its own won-
derful ways, and on Linux youll have Firefox or maybe Ice
Weasel if youre one of those Debian Communists.
Chapter One - JavaScript Goes Forth! 12
Beyond that, most operating systems these days come with
some sort of Text Editor that you can use to write your
code. For example, Microsoft comes with Notepad, Mac
OS comes with TextEdit, and Linux comes with a behemoth
piece of shit called Emacs that the obese Jesus-bearded guys
seem to like. There are definitely better editors, but you
should learn how to actually write code first.
That said, even though I could tell you to crack open your
Web Browser and a Text Editor, Im not going to do that.
One of the best ways to learn a language is via discovery,
and me telling you to type a bunch of shit into a Text Editor,
save it to your hard drive, and then load it into a Browser
only inhibits your ability to discover. So I wont be that
kind of an asshole yet.
Instead, Im gonna be the kind of asshole who tells you that
you need to install something from the Internet. Specifi-
cally, you need to install Node.js. Mind you, we wont be
doing any real Node.js programming until later in the book,
but Node has an excellent tool that you can use to discover
all of the wonderful eccentricities that JavaScript plans to
hoist on you.
Installing Node.js
If youre using Windows or a Mac, then youll need to
point your Web Browser at Nodejs.org and download the
installer. The web site will explain how to do this, so Im
not gonna waste my breath. Its really not difficult, so if
youre lost already, then you may want to close the book,
Chapter One - JavaScript Goes Forth! 13
walk away from your desk, and start a rewarding career
painting fruit or something.
If youre not using Windows or a Mac, then youre prob-
ably one of the 1% of masochists out there who are using
Linux. If you dont know what Linux is, dont worry, its
not important. Sufficed to say its an Operating System
written by nerds, and apparently written only for nerds
since they really havent been able to get the thing to a
usable state for normal users.
If youre using Ubuntu Linux, which is probably the only
flavor of Linux thats close to usable, then you can install a
not-very-up-to-date version of Node using the apt package
manager like so:
1 sudo apt-get install nodejs
If youre not using Ubuntu, then Im sure there are other
package managers that feature Node.js, but I have no idea
what youd have to do to install it. Instead, Id probably
suggest downloading the source code from the Node.js
web site and following the installation instructions. Hey,
dont complain! Youre a Linux user, this type of bullshit
shouldnt be new to you! You bought into the nightmare
when you installed the operating system.
The Node.js REPL
Alright, so lets assume youve installed Node.js. Now
youre asking yourself Why the hell did I just install
Chapter One - JavaScript Goes Forth! 14
Node.js?
The very simple answer is for its REPL.
REPL? you ask, What the fuck is REPL? Is that a sexually
transmitted disease or something?
Yes.
Okay, no. The Node.js REPL is a program that you use
to issue JavaScript instructions. The letters REPL stand for
Read, Eval, Print Loop which is actually self-describing if
you knowanything about programming, but since I assume
you dont, let me talk about that a little.
Read means the program reads your instructions
Eval is short for Evaluate and means that the pro-
gramwill then attempt to performthose instructions.
Nerds like to shorten things because theyre lazy.
Theyre also so arrogant that they just assume youll
understand what theyre talking about.
Print means it will display the result of those in-
structions to you
Loop means youll be able to do it over and over
To start the Node.js REPL, youll have to use your Oper-
ating Systems Terminal program. On Mac OS X, you can
find it in Applications -> Utilities -> Terminal. On Ubuntu
Linux, its called gnome-terminal or something Terminal-
like. On Windows, it used to be called cmd.exe, but I have
Chapter One - JavaScript Goes Forth! 15
no fuckin idea what theyre calling it these days, so youll
have to figure that out for yourself, sorry.
Anyway, once youre in your Terminal program, you sim-
ply type the following:
1 ~$ node
The Node.js REPL will then start up, giving you a prompt
that looks something like this.
1 >
So what I want you to do is type the following:
1 > .help
You should now see something like the following:
1 > .help
2 .break Sometimes you get stuck, this gets you out
3 .clear Alias for .break
4 .exit Exit the repl
5 .help Show repl options
6 .load Load JS from a file into the REPL session
7 .save Save all evaluated commands in this REPL session to a file
Youll notice that you can type .exit to exit the REPL. If
you forget this, you can also type Ctrl-C a couple of times
to kill it.
Chapter One - JavaScript Goes Forth! 16
Your First Shitty Program
As the saying goes, theres no better time than the present,
right? Lets write your first JavaScript program. Nor-
mally, an author will do something lame like print out
Hello World!, but I refuse to believe youre too stupid to
handle more than that. So what I want you to do is read the
following lines of code and type them into the Node REPL
verbatim:
1 > var count = 0;
2 > while ( count < 100 ) {
3 ... console.log("Hello, Asshole! How you like these apples?");
4 ... count = count + 1;
5 ... }
Did you type them verbatim? Dont tell me later that you
wrote Hello, Todd instead of Hello, Asshole! or Ill be
really pissed off.
After you type Enter at the end of the last line, youll
notice something. A bunch of shit printed out on your
screen. Annoying as fuck, aint it!? Rethinking your choice
to learn JavaScript? Keep your pants on, Ill make it sexy
for you!
1 Hello, Asshole! How you like these apples?
2 Hello, Asshole! How you like these apples?
3 Hello, Asshole! How you like these apples?
Chapter One - JavaScript Goes Forth! 17
4 Hello, Asshole! How you like these apples?
5 Hello, Asshole! How you like these apples?
6 Hello, Asshole! How you like these apples?
7 ...
Breaking it Down
Alright, so there is a lot to digest in these few lines of code.
1 var count = 0;
Here we are creating something called a variable and
assigning it a value of 0. In this case the variable is named
count, but it could have just as easily been called cnt
JavaScript will not censor you.
1 while ( count < 100 ) {
The line that begins with while is the good shit! while is
whats called a statement in JavaScript, and is a way to
tell it to repeat a set of instructions so long as a particular
condition is met. In this case, that condition is the value
pointed to by the count variable being less than 100.
1 console.log("Hello, Asshole! How you like these apples?");
The next line is the beginning of a function call. A function
is the basic unit of instruction re-use in JavaScript. If you
Chapter One - JavaScript Goes Forth! 18
paid attention in math class, youll know what a function
is, otherwise youre probably blinking your eyes repeatedly
in utter confusion right now. Just know that were calling
a function named log that belongs to an object called
console and handing to it something that it needs to tell
you And it will tell you a hundred times!
1 count = count + 1;
This is an assignment expression, and it will increment the
value pointed to by the count variable. What I mean by
this is that it will take whatever value count previously
pointed to, add 1 to that value, and then point count at
this new value. This line is important because if we dont
increment count, the condition that is tested on our while
line will never be met.
1 }
The last line closes the loop that was started with the while
statement on the second line. What this means is that
everything between the opening { and closing } will be
repeated as part of the loop, in this case our call to the log
function.
So what happens if you forgot to add the count = count
+ 1; line? You should try it! But be prepared to kill
your Terminal program or reboot your computer, because
otherwise its gonna be a long day waiting for the program
to finish.
Chapter One - JavaScript Goes Forth! 19
TODO: This will be an aside
This idea of opening and closing is important to most
programming languages. What it does is establish some-
thing called a block, which is often used as a way of
defining repeatable or conditional instructions.
For example, say you have twenty kittens that need to
be shaved. You could write a program that instructs the
computer to do it with twenty lines of code, one line
for each kitten shaving instruction, or you could write a
program that instructs the computer to do it in five lines of
code (or maybe even one!) using a while loop.
TODO: Awesome picture of Kitten Shaving Efficiency
Wrapping it Up
Weve just scratched the surface of this program. Theres
so much more to learn just about these few lines of code
that it might just cause your head to explode! For example,
whats this var shit about? And why do I have quotation
marks around the words Imgoing to display on the screen?
These questions, and more, will be answered, but first, we
should talk about data, because if you dont know what
data is and how a computer program interacts with it, then
youre going to be completely fucking lost going forward.
Chapter One - JavaScript Goes Forth! 20
Data, Hes An Android, Right?
Data is what its all about my friends. Without data, a
computer would have absolutely nothing to do. It would
live an existence much like a fat guy that ran out of bacon
and French fries. Without the ability to jam his face full of
food, he would be mostly idle, he might even have to find
things to do to relieve his boredom. My god, he might even
decide to go jogging!
Unfortunately, a computer cant decide what to do when it
gets bored. You have to give it something it can chew on,
and in 100% of all these cases, youre giving it data.
Okay, so what is data?
Data is information and it can be managed and represented
in a bunch of ways. For example: The fat guy I spoke about
earlier? He weighs about 350lbs in Imperial measurements.
In this case, the data is a number. Interestingly enough, that
number is easily converted, for example it can be translated
to kilograms to appease you European types, but at the
end of the day were talking about the same thing.
But fat boy also has a name, doesnt he? Lets call him
William, as in Will the Whale. His name is also data, but
in this case its a sequence of letters that form a word. Hes
unfortunate in that his name is such a great candidate for
alliteration, and so Im sure hes been tortured all of his fat
life, therefore it wont hurt to fuck with him some more.
unless such a marriage is illegal in your state
Chapter One - JavaScript Goes Forth! 21
And surely Will the Whale was born at some point, right?
I have it on good authority that he was born on March
5, 1987. Thats right around the time Americans were
becoming grossly obese, but nevermind that. In this case,
his birthdate is also data, albeit a little more complex than
his weight or name, but data nonetheless.
What I just described to you are three types of data. The
word type is important because youll hear it often when
people are classifying data. In JavaScript, a series of letters
is known as a String, a number is known as a wait for it
Number, and a date, youre not gonna believe it, is known
as a Date. There are other types, but well get into those
later. For now its just important to understand that there
are different types.
Introducing Objects
So what do these three types of data have in common? In
the real world, very little, because a number is a number,
a name is a name, and a date is a date, but in JavaScript
they are all treated as something called an Object. I almost
want to avoid talking about what an Object is at this point
because its not terribly important, and I also think the
name Object may be the stupidest fucking moniker of all
time. Nevertheless, here we go:
An object is data that may or may not be married to some
code. [1]
Mind you, this is not the textbook definition. Its not even
Chapter One - JavaScript Goes Forth! 22
the correct definition from a purist standpoint, but its the
best way to explain it to you at this point. So what does it
mean?
Well, as an example, lets talk about dates. On its own a
Date is as boring and useless as nipples on men. It can tell
us only one thing, but what if we wanted to find out more?
For example, what will the date be seven days from now?
If its the fifth of the month, thats easy to guess, but its
not so easy to determine if its the twenty-seventh day of
the month, especially if its February.
So wouldnt it be nice if you could ask a Date a question like
that? Well lucky you, you can! This is where that married
to some code thing comes into play. Try this in the Node.js
REPL:
1 > new Date();
It will display something like:
1 Thu Jul 26 2012 19:18:45 GMT+0200 (CEST)
The current date and time! Or at least that was the
current date and time when I wrote this. In case you
were interested, I was on a train traveling from Berlin to
a shithole called Braunschweig. I highly recommend you
go there, if only because I want you to suffer as much as I
have.
Now do the following:
Chapter One - JavaScript Goes Forth! 23
1 > var d = new Date();
What youve just done is create a new Date object and
assigned its value to a variable named d. Ill be talking
about what variables are in the next section, so keep your
pants on, because first I want to show you the fun stuff
type d. and press your [Tab] key!
A whole bunch of shit just spit out onto the screen! Heres
some of the more important stuff though:
1 d.constructor d.getDate d.getDay
2 d.getFullYear d.getHours d.getMilliseconds
3 d.getMinutes d.getMonth d.getSeconds
4 d.getTime d.getTimezoneOffset d.getUTCDate
5 d.getUTCDay d.getUTCFullYear d.getUTCHours
6 d.getUTCMilliseconds d.getUTCMinutes d.getUTCMonth
7 d.getUTCSeconds d.getYear d.setDate
8 d.setFullYear d.setHours d.setMilliseconds
9 d.setMinutes d.setMonth d.setSeconds
10 d.setTime d.setUTCDate d.setUTCFullYear
11 d.setUTCHours d.setUTCMilliseconds d.setUTCMinutes
12 d.setUTCMonth d.setUTCSeconds d.setYear
13 d.toDateString d.toGMTString d.toISOString
14 d.toJSON d.toLocaleDateString d.toLocaleString
15 d.toLocaleTimeString d.toString d.toTimeString
16 d.toUTCString d.valueOf
This is a feature of the Node REPL called Code Comple-
tion and what its doing is taking your variable and telling
Chapter One - JavaScript Goes Forth! 24
you what it knows about it. Specifically, there are a bunch
of things that a Date can do and most of them seem related
to working with Dates. GO FIGURE!
Youre seeing this because a Date in JavaScript is not just
a simple value, but an object that has code married to it.
And Dates are just the tip of the iceberg.
Variables, Whats That All About?
Ive heard variables described as buckets before, but I
dont like that definition because in the real world a bucket
is a physical object that can be passed around just like its
contents. This creates an existential paradox by which the
world could explode, or at least your brain if you think
about it for too long.
So what is a variable? A variable is just a way you refer
to something Its a name. My name is Thom but the
name itself doesnt exist in the physical world, its just a
way to refer to me in a conversation or in an email or on a
tax form. For example, you might be talking to your friend
and say Hey, that Thom is a real asshole. Youd be right.
Youd be justified. Youd probably become my best friend.
But Thom isnt my only name. Some people call me
Thomas, others call me Bradford and my mother calls
me Tommy but if you ever call me Tommy, you will not
be my best friend. Only Mom is allowed to do that. The
point Im making is that there is only one of me, and Im
pretty awesome, but there are many ways to refer to me.
Chapter One - JavaScript Goes Forth! 25
The same applies to variables. Multiple variables can refer
to a single value.
So when we wrote var d = new Date() we were creating a
new Date object, but d isnt the object, its just a name that
refers to it. Want proof? Trying to do the following:
1 > var d = new Date();
2 > var x = d;
Now both d and x refer to the same object. Dont believe?
Try it:
1 > d
2 Thu Jul 26 2012 19:18:45 GMT+0200 (CEST)
3 > x
4 Thu Jul 26 2012 19:18:45 GMT+0200 (CEST)
See how variables and data arent inextricably linked?
Good. So are we finished on the subject of variables? Not
really, but lets move on anyway. This chapters getting
too long.

S-ar putea să vă placă și