A brief aside on JavaScript Important JavaScript Concepts

berserkarithmeticInternet και Εφαρμογές Web

14 Δεκ 2013 (πριν από 3 χρόνια και 9 μήνες)

114 εμφανίσεις

A brief aside on JavaScript
JavaScript is an object-oriented scripting language invented by Netscape
1
.
Client-side JavaScript, which is what we are primarily concerned with, is an
extension of the core of JavaScript that allows us to dynamically
manipulate our HTML pages, as well as monitor for and respond to events
on the page. Together with the DOM, JavaScript gives us access to events
not available to us with only HTML and CSS, including events that tell us
“the website has finished loading” and “the visitor has clicked on this
element”.
Important: What is the DOM?
In JavaScript we make use of the Document Object Model: the DOM for
short. The DOM is how the browser views HTML. Instead of HTML
appearing as elements, the browser gets the document as a nested list of
nodes, also called the DOM Tree. We can then ask the DOM for nodes in
the tree, and then manipulate them. You can think of this as asking the
DOM to grab specific HTML elements on the page for us, which we can
then modify. The DOM gives us access to elements on the page. Once we
have access to them, we can use JavaScript to manipulate them.
To learn more about the DOM, Mozilla has an excellent write-up at:
https://developer.mozilla.org/en/DOM/About_the_Document_Object_Model

Important JavaScript Concepts
JavaScript is a large topic that fills entire books, but we wanted to review a
few key concepts that you will see in our code snippets.
Adding JavaScript to your page
1
1
http://en.wikipedia.org/wiki/JavaScript#History
Much like with CSS, we can place our JavaScript in the head element of
our HTML page, or in its own separate file. If we place it in the head
element, we must surround the code with <script> tags:
<script type="text/javascript">
!/* code goes here! */
</script>
We can also include the JavaScript as a separate file, and place a link to
that in our head element. The downside of this approach is that it means
the page will not load until all the JavaScript is downloaded. A better
approach, if we are linking to separate JavaScript files, is to place the links
to the scripts at the bottom of the page, just before the closing body tag.
This will help prevent the slowdown we described.
Note: Comments in JavaScript
Just like in CSS, we can write comments in JavaScript. One difference
between comments in JavaScript and comments in CSS is that in addition
to comments that start with /* and end with */, there is also the concept of a
one-line comment. One line comments start with two backslashes: “//”.
So, we could have also written our comment like this:
<script type="text/javascript">
!// code goes here!
</script>
Functions
JavaScript allows you to group code together into
functions
. Functions
allow us to save ourselves time. Let’s say we have three lines of code that
perform a specific task. Rather than writing the same three lines of code in
two different places, we can organize those three lines into a function.
Then, we can simply call that function any time we need to run that code.
This saves us time and helps us organize our code better.
A function looks like this:
function sayHello()
{
2
!
}
You begin a function with the word “function”. The second word is the name
of the function, which is how you can call it elsewhere on the page. In our
case, the function name is “sayHello”.
The code that makes up the function goes in between the two curly
brackets:
function sayHello()
{
!alert(“Hello!”);
}
W e i n d i c a t e t h e e n d o f a l i n e o f c o d e w i t h a s e m i c o l o n. T h e s e m i c o l o n t e l l s
t h e b r o w s e r w h e r e o n e i n s t r u c t i o n e n d s a n d a n o t h e r o n e b e g i n s. I t a c t s
m u c h l i k e t h e p e r i o d d o e s i n s e n t e n c e s: i t t e l l s u s w h e n t h e y a r e o v e r,
s e p a r a t i n g t w o l i n e s o f t e x t.
N o t e: F u n c t i o n v s M e t h o d
Y o u m a y h a v e a l s o h e a r d t h e w o r d
m e t h o d
. A m e t h o d i s a f u n c t i o n t h a t i s
a s s o c i a t e d w i t h a p a r t i c u l a r
object
. The APIs we will be learning about
define their functions as a part of specific objects, so when we talk about
the tasks the APIs allow us to do, we will be referring to them as methods.
Remember the DOM?
alert
is a DOM method. It generates a pop-up
window. What is the “Hello!” in the parentheses? It is an
argument
.
Arguments
As argument is any value that a function needs in order to perform its task.
In the case above, the
alert
method will use the argument’s value
(“Hello!”) to print out a message.
Some functions take arguments, and some don’t. If you don’t have any
arguments for a particular function, you will simply end the function name
with a set of empty parentheses, like in
sayHello()
.
3
If, instead of
sayHello
we had a function called
saySomething
where
we could specify what, exactly, we wanted to say. We would define that
function like this:
function saySomething(whatToSay)
{
alert(whatToSay);
}
whatToSay
is the argument. We would call the
whatToSay
function like
this:
saySomething(“Goodbye!”);
Calling JavaScript Functions
There’s one final step, and that is telling our HTML page to run the
sayHello
function. We are going to tell our page to run sayHello once the
page has loaded.
There is an event defined in the DOM called the onLoad event. It occurs
when the entire HTML page has loaded, including all the images. We can
ask our page to run sayHello like this:
<body
onLoad=”sayHello()”
>
Here’s what
alert(“Hello!”);
generates:
4
alert-window.png - The alert DOM function creates a new dialog window
Variables
Just like in Math class, variables in programming allow us to store values in
them. But unlike Math class, we can store all kinds of things in variables:
numbers, text (usually called
strings
in programming), true/false values
(called
booleans
) and
objects
.
In JavaScript, you create a new variable by using the
var
keyword, and
then giving your variable a name. This is also called variable
declaration
.
We could add a variable to our example like this:
function sayHello()
{
!
var textToPrint = “Hello!”;
!alert(
textToPrint
);
}
Objects
Sometimes, you need a way of representing something complex. You need
to define something more complicated than a number or a string.
5
Perhaps you want to describe a person’s physical location, as the
Geolocation API does. What would you need to represent that? Well, at the
minimum, you would need their latitude and longitude. We could store
these values separately in two different variables, but wouldn’t it be nice to
store them together as a single unit? And people do tend to move around!
So it may be helpful to know
when
we asked for their current latitude and
longitude. Was it five seconds ago, or two hours ago, or a week ago? Now
we have three variables to keep track of.
A different way to organize these three pieces of information would be to
create an object. Objects allow us to say, for example, “the way you
describe a GPS position is with a latitude, a longitude, and a timestamp.”
Properties
The last JavaScript concept we’ll review is that of
properties
. It’s important
for our purposes because Modernizr makes use of them.
You can think of a property as one of the variables that make up an object.
In our theoretical GPS position example, the latitude, longitude and
timestamp are all properties.
We access the values stored in properties by putting a period “.” after the
object and then specifying the name of the property. For example:
object.propertyName
. This is known as “dot syntax”.
Let’s assume we have an object position. We could access information
about the timestamp property by calling
position.timestamp.
if...else Statements
if...else statements let us ask questions and take actions depending on the
answers. The questions we ask always have a yes or no answer. They are
either true or false.
if...else statements allow us to run different code depending on the answers
to our questions. Here is a very simple example, which tests whether or not
a variable
x
is greater than four:
var x = 5;
if (x > 4)
6
{
alert(“x is greater than four!”);
}
else
{
alert(“x is less than four!”);
}
If our example, since we have set
x = 5
, only the code inside the
if
statement will run. We will never reach the code inside the
else
statement.
A more realistic example may set
x
to be the value our visitor specifies in a
form.
Where to go to learn more
While we hope you now have a sense of the basics, JavaScript is an
enormous topic. To learn more, you may find the Mozilla Developer
Network’s JavaScript Guide useful
2
.
7
2

https://developer.mozilla.org/en/JavaScript/Guide
1.
8