Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training,
learning paths, books, tutorials, and more.

Chapter 4. JavaScript Functions and Objects: Serious JavaScript

Can you call yourself a scripter yet? Probably—you already know your way around a lot of JavaScript. But who wants to be a scripter when you can be a programmer? It’s time to get serious and take it up a notch—it’s time you learn about functions and objects. They’re the key to writing code that is more powerful, better organized and more maintainable. They’re also heavily used across HTML5 JavaScript APIs, so the better you understand them the faster you can jump into a new API and start ruling with it. Strap in, this chapter is going to require your undivided attention...

Expanding your vocabulary

You can already do a lot with JavaScript, let’s take a look at some of the things you know how to do:

So far, though, a lot of your knowledge is informal—sure, you can get an element out of the DOM and assign some new HTML to it, but if we asked you to explain exactly what document.getElementById is technically, well, that might be a little more challenging. No worries; by the time you leave this chapter you’re going to have it down.

Now to get you there, we’re not going to start with a deep, technical analysis of getElementById, no no, we’re going to do something a little more interesting: We’re going to extend JavaScript’s vocabulary and make it do some new things.

How to add your own functions

You’ve been using built-in functions, like alert, or even Math.random, but what if you wanted to add your own? Let’s say we wanted to write some code like this:

Create a checkGuess function

How a function works

So how does this all work? What happens when we actually invoke a function? Here’s the 10,000-foot view:

Okay, first we need a function.

Let’s say you’ve just written your new bark function, which has two parameters, dogName and dogWeight, and also a very impressive bit of code that returns a dog’s bark, depending on its weight of course.

Now let’s invoke it!

You know how to call a function already: just use its name and give it any arguments it needs. In this case we need two: a string with the dog’s name, and the dog’s weight, which is an integer.

Let’s make that call and see how this works:

And, let the body of the function do its work.

After we’ve assigned the value of each argument to its corresponding parameter in the function—like “Fido” to dogName and the integer 50 to dogWeight—then we’re ready to evaluate all the statements in the function body.

Statements are evaluated from top to bottom, just like all the other code you’ve been writing. What’s different is that we’re doing it in an environment where the parameter names dogName and dogWeight are assigned to the arguments you passed into the function.

Optionally, we can have return statements in the body...

... and that’s where we return a value back to the code that makes the call. Let’s see how that works:

Note

Remember, functions aren’t required to return a value. But in this case, the bark function does return a value.

If we could have another moment to talk...

We know, we know, by Chapter 4 you thought you’d be flying in an HTML5 jetpack by now, and we’ll get there. But before we do, you really need to understand the underpinnings of the HTML5 JavaScript APIs, and we’re going to do that in this chapter.

So what are these underpinnings? Think of the HTML5 JavaScript APIs as made up of objects, methods (otherwise known as functions) and properties. And so to really get in and master these APIs, you need to understand those things pretty well. Sure, you could try to get by without knowing them, but you’ll always be guessing your way around the APIs while failing to use them fully (not to mention making lots of mistakes and writing buggy code).

So we just wanted to drop you a note before you got too far into this chapter to tell you what we are up to. Here’s the great thing: by the end of this chapter you’re going to understand objects, functions, methods and a lot of other related things better than about 98% of JavaScript scripters out there. Seriously.

The Function Exposed

This week’s interview: a few things you didn’t know...

Head First: Welcome Function! We’re looking forward to digging in and finding out what you’re all about.

Function: Glad to be here.

Head First: Now we’ve noticed many people who are new to JavaScript don’t tend to use you a lot. They just get in and write their code, line by line, top to bottom. Why should they take a look at you?

Function: Yes, and that is unfortunate, because I’m powerful. Think about me like this: I give you a way to take code, write it once, and then reuse it over and over.

Head First: Well, excuse me for saying this, but if you’re just giving them the ability to do the same thing, over and over...that’s a little boring isn’t it?

Function: No no, functions are parameterized—in other words, each time you use the function, you pass it arguments so that you can get back results that vary, depending on what you pass in.

Head First: Err, example?

Function: Let’s say you need to tell your users how much the items in their shopping cart are going to cost, so you write a function computeShoppingCartTotal. Then you can pass that function different shopping carts belonging to different users and each time you get the appropriate cost of the shopping cart.

...By the way, back to your comment about new coders not using functions; that’s simply not true, they use them all the time: alert, document.getElementById, Math.random. They just aren’t defining their own functions.

Head First: Well, right, alert, that makes sense, but the other two don’t look quite like functions.

Function: Oh they’re functions, you see... hold on just a sec...

...oh, I was just told the readers haven’t learned about those kinds of functions yet, but they’re getting there in a few pages. Anyway, functions are everywhere.

Head First: So, one thing a function has to do is return a value, right? I mean, what if I don’t have a value I want to return?

Function: Many functions return values, but a function doesn’t have to. Lots of functions just do something like update the DOM and then return without any value, and that’s just fine.

Head First: So in those functions I just don’t have a return statement?

Function: You got it.

Head First: Well, what about naming your functions, I’ve heard you don’t have to do that either, if you don’t want to.

Function: Okay, let’s not freak the audience out too much. How about we come back to that topic after they know a bit more about me?

Head First: As long as you give me an exclusive?

Function: We’ll talk...

No, they’re different.

When you define a function you can define it with one or more parameters.

When you call a function, you call it with arguments:

So you’ll only define your parameters once, but you’ll probably call your functions with a lot of different arguments.

Note

You’d be amazed how many people get this wrong—even books get it wrong, so if you read it differently elsewhere, now you know better....

You define a function with parameters, you call a function with arguments.

Anatomy of a Function

Now that you know how to define and call a function, let’s make sure we’ve got the syntax down cold. Here are all the parts of a function’s anatomy:

There are no Dumb Questions

Q:

Q: Why don’t the parameter names have var in front of them? A parameter is a new variable right?

A:

A: Efffectively yes. The function does all the work of instantiating the variable for you, so you don’t need to supply the var keyword in front of your parameter names.

Q:

Q: What are the rules for function names?

A:

A: The rules for naming a function are the same as the rules for naming a variable.

Q:

Q: I’m passing a variable to my function—if I change the value of the corresponding parameter in my function does it also change my original variable?

A:

A: No. When you pass a primitive value it is copied into the parameter. We call this “passing by value.” So if you change the value of the parameter in your function body it has no affect on our original argument’s value. The exception to this is passing an array or object, and we’ll get to that in a bit.

Q:

Q: So how can I change values in a function?

A:

A: You can only change the values of global variables (those defined outside of functions), or variables you’ve explictly defined in your function. We’re going to talk about that in a little more detail shortly.

Q:

Q: What does a function return if it doesn’t have a return statement?

A:

A: A function without a return statement returns undefined.

Sharpen your pencil

Use your knowledge of functions and passing arguments to parameters to evaluate the code below. After you’ve traced through the code, write the value of each variable below. Check your answers with the solution at the end of the chapter before you go on.

Local and Global Variables

Know the difference or risk humiliation

You already know that you can declare a variable by using the var keyword and a name anywhere in your script:

And you’ve seen that you can also declare variables inside a function:

If a variable is declared outside a function, it’s GLOBAL. If it’s declared inside a function, it’s LOCAL.

But what does it matter? Variables are variables, right? Well, where you declare your variables determines how visible they are to other parts of your code, and, later, understanding how these two kinds of variables operate will help you write more maintainable code (not to mention, help you understand the code of others).

Knowing the scope of your local and global variables

Where you define your variables determines their scope; that is, where they are defined and where they aren’t, where they’re visible to your code and where they aren’t. Let’s look at an example of both locally and globally scoped variables—remember, the variables you define outside a function are globally scoped, and the function variables are locally scoped:

The short lives of variables

When you’re a variable, you work hard and life can be short. That is, unless you’re a global variable, but even with globals, life has its limits. But what determines the life of a variable? Think about it like this:

Globals live as long as the page. A global variable begins life when its JavaScript is loaded into the page. But, your global variable’s life ends when the page goes away. Even if you reload the same page, all your global variables are destroyed and then recreated in the newly loaded page.

Local variables typically disappear when your function ends. Local variables are created when your function is first called and live until the function returns (with a value or not). That said, you can take the values of your local variables and return them from the function before the variables meet their digital maker.

Note

We say “typically” because there are some advanced ways to retain locals a little longer, but we’re not going to worry about them now.

So, there really is NO escape from the page is there? If you’re a local variable, your life comes and goes quickly, and if you’re lucky enough to be a global, you’re good as long as that browser doesn’t reload the page.

But there just has to be a way to escape the page! We can find a way! Can’t we?

Note

Join us in the Web Storage chapter where we’ll help our data escape the dreaded page refresh!

You “shadow” your global.

Here’s what that means: say you have a global variable beanCounter and you then declare a function, like this:

When you do this, any references to beanCounter within the function refer to the local variable and not the global. So we say the global variable is in the shadow of the local variable (in other words we can’t see it because the local version is in our way).

Note

Note that the local and global variables have no effect on each other: if you change one, it has no effect on the other. They are independent variables.

There are no Dumb Questions

Q:

Q: Keeping track of the scope of all these locals and globals is confusing, so why not just stick to globals? That’s what I’ve always done.

A:

A: If you’re writing code that is complex or that needs to be maintained over a long period of time, then you really have to watch how you manage your variables. When you’re overzealous in creating global variables, it becomes difficult to track where your variables are being used (and where you’re making changes to your variables’ values), and that can lead to buggy code. All this becomes even more important when you’re writing code with coworkers or you’re using third-party libraries (although if those libraries are written well, they should be structured to avoid these issues).

Note

If this were a book on in-depth JavaScript programming we’d take you further into this topic, but given that this is Head First HTML5 Programming, we’ll just suggest you explore this topic further to improve the quality of your code!

So, use globals where it makes sense, but use them in moderation, and whenever possible, make your variables local. As you get more experience with JavaScript, you can investigate additional techniques to structure code so that it’s more maintainable.

Q:

Q: I have global variables in my page, but I’m loading in other JavaScript files as well. Do those files have separate sets of global variables?

A:

A: There is only one global scope so every file you load sees the same set of variables (and creates globals in the same space). That’s why it is so important you be careful with your use of variables to avoid clashes (and reduce or eliminate global variables when you can).

Q:

Q: I’ve seen code where people don’t use the var keyword when assigning a value to a new variable name. How does that work?

A:

A: Yes, that can be done; when you assign a value to a variable name that hasn’t been previously declared, it is treated as a new, global variable. So be careful, if you do this within a function you are creating a global variable. Note that we don’t recommend this coding practice; not only is it potentially confusing when reading code, some people think this behavior may change some day in the JavaScript implementations (which would probably break your code).

Q:

Q: Do I need to define a function before I use it, or can it appear anywhere in my script?

A:

A: Function declarations can appear anywhere in your script. You can declare a function below where you use it if you want. This works because when you first load your page, the browser parses all the JavaScript in the page (or in the external file) and sees the function declaration before it starts executing the code. You can also put your global variable declarations anywhere in your script, although we recommend declaring all your global variables at the top of your files so they’re easy to locate.

One thing to keep in mind when using more than one external JavaScript file is that if you have two functions in different files named the same thing, the function that the browser sees last will be the one that is used.

Q:

Q: Everyone seems to complain about the overuse of global variables in JavaScript. Why is this? Was the language badly designed or do people not know what they’re doing, or what? And what do we do about it?

A:

A: Globals are often overused in JavaScript. Some of this is because the language makes it easy to just jump in and start coding—and that’s a good thing—because JavaScript doesn’t enforce a lot of structure or overhead on you. The downside is when people write serious code this way and it has to be changed and maintained over the long term (and that pretty much describes all web pages). All that said, JavaScript is a powerful language and includes features like objects that you can use to organize your code in a modular way. Many books have been written on that topic alone, and we’re going to give you just a taste of objects in the second half of this chapter (which is only a few pages away).

Oh, did we mention functions are also values?

OK, you’ve used variables to store numbers, boolean values, strings, arrays, all kinds of things, but did we mention you can also assign a function to a variable? Check this out:

Well, not only did we fail to mention this little detail about functions before now, but we also weren’t totally honest when we told you about the anatomy of a function—as it turns out, you don’t even have to give your function a name. That’s right: your function can be anonymous. What the heck does that mean, and why would you want to do such a thing? First let’s see how you create a function without a name:

Brain Power

Take a look at this code: what do you think is going on?

This should start to look a little more understandable with what we just covered...

What you can do with functions as values

So what’s the big deal? Why is this useful? Well, the important thing isn’t so much that we can assign a function to a variable, that’s just our way of showing you that a function actually is a value. And you know you can store values in variables or arrays, you can pass them as arguments to functions, or as we’ll soon see, you can assign them to the properties of objects. But, rather than talking you through how anonymous functions are useful, let’s just look at one of the many ways using functions as values starts to get interesting:

Or we could get even fancier:

You might be starting to see that functions can do some useful things beyond just packaging up code for reuse; to give you a better idea of how to fully take advantage of functions, we’re going to take a look at objects and see how they fit into JavaScript, and then we’ll put it all together.

Well we thought we’d covered that already... but if it looks like we’ve picked you up and have driven you halfway around the city with the meter running (when we could have driven you straight downtown), well, then remember we’re about to start diving into the APIs that work with HTML5 in the next chapter. And, doing that is going to require that you really understand functions, objects and a few other related topics.

So hang in there—in fact you’re halfway there! And don’t forget, this is the chapter where you’re going from scripter to programmer, from an HTML/CSS jockey to someone who is capable of building real apps.

Note

Did we already mention that is probably going to make you a lot more money too?

Did someone say “Objects”?!

Ah, our favorite topic! Objects are going to take your JavaScript programming skills to the next level—they’re the key to managing complex code, to understanding the DOM, to organizing your data, and they’re even the fundamental way HTML5 JavaScript APIs are packaged up (and that’s just our short list!). That said, objects are a difficult topic, right? Hah! We’re going to just jump in head first and you’ll be using them in no time.

Here’s the secret to JavaScript objects: they’re just a collection of properties. Let’s take an example, say, a dog. A dog’s got properties:

Thinking about properties...

Of course Fido would be the first to admit there’s a lot more to him than just a few properties, but for this example, those are going to be the ones we need to capture in software. Let’s think about those properties in terms of JavaScript data types:

How to create an object in JavaScript

So we’ve got an object with some properties; how do we create this using JavaScript? Here’s how:

Some things you can do with objects

Access object properties with “dot” notation:

Access properties using a string with [] notation:

Change a property’s value:

Enumerate all an object’s properties:

Have fun with an object’s array:

Pass an object to a function:

Note

The Dot Operator.

The dot operator (.) gives you access to an object’s properties. In general it’s easier to read than the [“string”] notation:

fido.weight is the size of fido.

fido.breed is the breed of fido.

fido.name is the name of fido.

fido.loves is an array containing fido’s interests.

Yes, you can add or delete properties at any time.

To add a property to an object you simply assign a new property a value, like this:

fido.age = 5;

and from that point on fido will have a new property: age.

Likewise, you can delete any property with the delete keyword, like this:

delete fido.age;

When you delete a property, you’re not just deleting the value of the property, you’re deleting the property itself. In fact, if you use fido.age after deleting it, it will evaluate to undefined.

The delete expression returns true if the property was deleted successfully (or if you delete a property that doesn’t exist or if what you’re trying to delete isn’t a property of an object).

Let’s talk about passing objects to functions

We’ve already talked a bit about how arguments are passed to functions—arguments are passed by value, so if we pass an integer, the corresponding function parameter gets a copy of the value of that integer for its use in the function. The same rules hold true for objects, however we’ve got to look a little more closely at what a variable holds when it is assigned to an object to know what this means.

When an object is assigned to a variable, that variable holds a reference to the object, not the object itself. Think of a reference as a pointer to the object.

So, when you call a function and pass it an object, you’re passing the object reference—not the object itself, just a “pointer” to it. A copy of the reference is passed into the parameter, which then points to the original object.

So, what does this all mean? Well, when you change a property of the object, you’re changing the property in the original object, not a copy, and so, you’ll see all the changes you make to an object within and outside of your function. Let’s step through an example using a loseWeight function for dogs...

Putting Fido on a diet....

Let’s take a look at what’s going on when we pass fido to loseWeight and change the dog.weight property.

Behind the Scenes

We’ve defined an object, fido, and we are passing that object into a function, loseWeight.

The dog parameter of the loseWeight function gets a copy of the reference to fido. And so, any changes to the properties of the parameter affect the object that was passed in.

Now Showing at the Webville Cinema

The Webville Cinema has come to us for help with their JavaScript API; let’s start simple and design the movie object for them. What we need is a couple of movie objects that each include a title, a genre, a movie rating (1-5 stars) and a set of showtimes. Go ahead and sketch out your movie object design here (you can use our dog object as a model). Here’s some sample data you can use to populate your objects:

Plan 9 from Outer Space, which shows at 3:00pm, 7:00pm and 11:00pm; it’s in the genre “cult classic”; and has a 2-star rating.

Forbidden Planet, which shows at 5:00pm and 9:00pm; is in the genre “classic sci-fi”; and has a 5-star rating.

Note

The solution’s right on the next page, but don’t look until you’ve done the exercise. Really. We mean it.

Note

Feel free to add your own favorites instead.

Note

Design your objects here.

Now Showing at the Webville Cinema: Solution

How did it go creating your movie object?

Here’s our solution:

Our next showing is at....

We’ve already had a small taste of mixing objects and functions. Let’s take this further by writing some code to tell us when the next showing of a movie is. Our function’s going to take a movie as an argument, and return a string containing the next time it plays, based on your current time.

How “Chaining” works...

Did you catch this in the previous code?

movie.showtimes.length

That doesn’t look like anything we’ve seen before. This is really just a shorthand for a series of steps we could have taken to get the length of the showtimes array from the movies object. We could have written this instead:

But we can do all this in one shot by chaining together the expressions. Let’s step through how this works:

Testing at the drive-in

Get the code on the previous page typed in and let’s give it a test run. You’ll see that the getNextShowing function takes whatever movie it is handed and figures out the next showing time. Feel free to create some new movie objects of your own and give them a test drive too. We did, at our own local time of 12:30pm:

Objects can have behavior too...

You didn’t think objects were just for storing numbers, strings and arrays did you? Objects are active, they can do things. Dogs don’t just sit there: they bark, run, play catch and a dog object should too! Given everything you’ve learned in this chapter, you’re all set to add behavior to your objects. Here’s how we do that:

When an object has a function in it, we say that object has a method.

To call a method on an object we use the object name along with the method using our dot notation, and supply any arguments needed.

Meanwhile back at Webville Cinema...

Now that your knowledge of objects is expanding we can go back and improve the cinema code. We’ve already written a getNextShowing function that takes a movie as an argument, but we could instead make this part of the movie object by making it a method. Let’s do that:

But we know that can’t be quite right...

We actually can’t just throw the function in this object because getNextShowing takes a movie argument, and what we really want is to call getNextShowing like this:

Alright, so how do we fix this? We’ve got to remove the parameter from the getNextShowing method definition, but then we need to do something with all the references to movie.showtimes in the code because, once we remove the parameter, movie will no longer exist as a variable. Let’s take a look...

Let’s get the movie parameter out of there...

We’ve taken the liberty of removing the movie parameter, and all the references to it. Which leaves us with this code:

Now what?

Alright, here’s the conundrum: we’ve got these references to the properties showtimes and title. Normally in a function we’re referencing a local variable, a global variable, or a parameter of the function, but showtimes and title are properties of the movie1 object. Well maybe this just works... it seems like JavaScript might be smart enough to figure this out?

Nope. It doesn’t work. Feel free to give it a test drive; JavaScript will tell you the showtimes and title variables are undefined. How can that be?

Okay, here’s the deal: these variables are properties of an object, but we aren’t telling JavaScript which object. You might say to yourself, “Well, obviously we mean THIS object, this one right here! How could there be any confusion about that?” And, yes, we want the properties of this very object. In fact, there’s a keyword in JavaScript named this, and that is exactly how you tell JavaScript you mean this object we’re in.

Now, the situation is actually a little more complicated than it appears here, and we’re going to get to that in a second, but for now we’re going to add the this keyword and get this code working.

Adding the “this” keyword

Let’s add this each place we specify a property, so that we’re telling JavaScript we want the property in this object:

A test drive with “this”

Go ahead and type in the code above and also add the getNextShowing function to your movie2 object (just copy and paste it in). Then make the changes below to your previous test code. After that give it a spin! Here’s what we got:

Ah, good eye.

You have great instincts if you recognized that we are duplicating code when we copy getNextShowing into more than one movie object. One of the aims of “object-oriented” programming is to maximize code reuse—here we’re not reusing any code, in fact we’re creating every object as a one-off, and our movie objects just happen to be the same by convention (and copying and pasting!). Not only is that a waste, it can be error prone.

There’s a much better way to do this using a constructor. What’s a constructor? It’s just a special function we’re going to write that can create objects for us, and make them all the same. Think of it like a little factory that takes the property values you want to set in your object, and then hands you back a nice new object with all the right properties and methods.

Let’s create a constructor...

How to create a constructor

Let’s make a constructor for dogs. We already know what we want our dog objects to look like: they have name, breed and weight properties, and they have a bark method. So what our constructor needs to do is take the property values as parameters and then hand us back a dog object all ready to bark. Here’s the code:

So let’s walk through this again to make sure we’ve got it. Dog is a constructor function and it takes a set of arguments, which just happen to be the initial values for the properties we want: name, breed and weight. Once it has those values, it assigns properties using the this keyword. It also defines our bark method. The result of all this? The Dog constructor returns a new object. Let’s see how to actually use the constructor.

Now let’s use our constructor

Now that we’ve got our factory built, we can use it to create some dogs. There’s only one thing we haven’t told you, which is that you need to call a constructor function in a special way by putting the keyword new before the call. Here are some examples:

Let’s review what’s going on here one more time: we’re creating three different dog objects, each with its own properties, using the new keyword with the Dog constructor that we created. The constructor returns a Dog object customized with the arguments we passed in.

Next, we call the bark method on each one—notice that we’re sharing the same bark method across all dogs, and when each dog barks, this points to the dog object that made the call. So if we call the bark method on fido, then, in the bark method, this is set to the fido object. Let’s look a little closer at how that happens.

How does this really work?

Behind the Scenes

Anytime we put this in the code of a method it will be interpreted as a reference to the object the method was called on. So, if we call fido.bark, then this is going to reference fido. Or, if we call it on our dog object tiny then this is going to reference tiny within that method call. How does this know which object it is representing? Let’s see:

Let’s say we’ve got a dog object assigned to fido:

And we call bark() on fido:

So “this” always refers to the object the method was invoked on, no matter how many dogs we create to bark:

Code Magnets

A working Movie constructor function was on the fridge, but some of the magnets fell on the floor. Can you help get it back together? Be careful, some extra magnets may have already been on the ground and might distract you.

Q: What’s the real difference between a function and a method? After all, if they’re the same thing why call them something different?

A:

A: By convention, if an object has a function we call that a method. They both work the same way, except that you invoke an object’s method using the dot operator, and a method can use this to access the object on which the method is invoked. Think of a function as a standalone piece of code you can invoke, and a method as behavior that is attached to a specific object.

Q:

Q: So when I create objects with a constructor and those objects have a method, then all of those objects share the same code for that method?

A:

A: That’s right, and that’s one of the advantages of object-oriented programming: you can create the code for that class of objects (say all your dog objects) in one place and all the dogs share it. Now the way you make it specific to each dog is with your properties and using this to access those properties.

Q:

Q: Can I set this to a value of my choosing, and if I do, will that mess things up?

A:

A: No, you can’t set this to anything. Remember, this is a keyword, not a variable! It looks and acts a bit like one, but it’s not a variable.

Q:

Q: Does this have a value outside of an object method?

A:

A: No, if you’re not invoking an object method, then this is undefined.

Q:

Q: So the way to think about this is when I invoke a method on an object, the value of this is set to that object the entire time the method is being evaluated?

A:

A: Within the body of the object, yes, this will always be the object itself. There are some advanced cases where it may not be true; for instance, things get more complicated when you have objects within objects, and if you start doing that, you’ll need to look up the semantics, but this is a good general rule.

Q:

Q: I’ve heard that in object-oriented programming I can have classes of objects and they can inherit from each other. Like, I could have a mammals class that both dog and cat inherit from. Can I do that in JavaScript?

A:

A: You can. JavaScript uses something called prototypal inheritance, which is an even more powerful model than strictly class-based models. Getting into prototypal inheritance is a little beyond the scope of this book, but who knows, we could be convinced to write more on JavaScript.

Q:

Q: So when we say new Date(), we’re using a constructor, right?

A:

A: Yes, good catch! Date is a built-in constructor in JavaScript. When you say new Date(), you get a Date object with a bunch of useful methods you can use to manipulate the date.

Q:

Q: What’s the difference between objects we write out ourselves and ones we create with a constructor?

A:

A: The main difference is how you create them. Objects you write out yourself using curly braces and comma separated properties are known as “object literals.” You literally type them into your code! If you want another one like it, you have to type it in yourself and make sure it’s got the same properties. Objects created by a constructor are created by using new and a constructor function, which returns the object. You can use the constructor function to create many objects that have the same properties, but different property values if you want.

Code Magnets

A working Movie constructor function was on the fridge, but some of the magnets fell on the floor. Can you help get it back together? Be careful, some extra magnets may have already been on the ground and might distract you.

Test drive your constructor right off the factory floor

Now that you’ve got a Movie constructor, it’s time to make some Movie objects! Go ahead and type in the Movie constructor function and then add the code below and take your constructor for a spin. We think you’ll agree this a much easier way to create objects.

Now, you might have started to notice...

...that objects are all around you. For instance, document and window are objects, as are the elements we get back from document.getElementById. And, these are just a few of many objects we’ll be encountering—when we get to the HTML5 APIs, we’ll be seeing objects everywhere!

Let’s take a second look at some of the objects you’ve been using all along in this book:

What is the window object anyway?

When you’re writing code for the browser, the window object is always going to be part of your life. The window object represents both the global environment for your JavaScript programs and the main window of your app, and as such, it contains many core properties and methods. Let’s take a look at it:

Window is the global object.

It may seem a little weird, but the window object acts as your global environment, so the names of any properties or methods from window are resolved even if you don’t prepend them with window.

In addition, any global variables you define are also put into the window namespace, so you can reference them as window.myvariable.

A closer look at window.onload

One thing we’ve used often so far in this book is a window.onload event handler. By assigning a function to the window.onload property, we can ensure our code isn’t run until the page is loaded and the DOM is completely set up. Now, there’s a lot going on in the window.onload statement, so let’s have another look and it will all start to come together for you:

Another look at the document object

The document object is another familar face; it’s the object we’ve been using to access the DOM. And, as you’ve just seen, it is actually a property of the window object. Of course we haven’t used it like window.document because we don’t need to. Let’s take a quick peek under the covers to see its more interesting properties and methods:

A closer look at document.getElementById

We promised in the begining of this chapter that you’d understand document.getElementById by the end of the chapter. Well, you made it through functions, objects, and methods, and now you’re ready! Check it out:

What was a confusing looking string of syntax now has a lot more meaning, right? Now, that div variable is also an object: an element object. Let’s take a closer look at that too.

One more object to think about: your element objects

We shouldn’t forget when we’re working with methods like getElementById that the elements they return are also objects! Okay, you might not have realized this, but now that you know, you might be starting to think everything in JavaScript is an object, and, well, you’re pretty much right.

You’ve already seen some evidence of element properties, like the innerHTML property; let’s look at some of the more notable properties and methods:

There are no Dumb Questions

Q:

Q: Since window is the global object, that means I can use its properties and all of its methods without specifying window first right?

A:

A: That’s right. And whether you prepend the window object’s properties and methods with window is up to you. For things like alert, everyone knows what that is, and no one uses window with it. On the other hand, if you’re using the lesser known properties or methods you might want to make your code more easily understandable, and use window.

A: Yes. But we don’t recommend it in this particular case, because there are a lot of objects that have onload properties, so your code is going to be much clearer if you use window. in front of onload.

Q:

Q: The reason we don’t say window.onload = init() is because that would call the function, instead of using its value?

A:

A: That’s right. When you use parentheses after the function name, like init(), you are saying you want to call the function init. If you use its name without parentheses, then you’re assigning the function value to the onload property. It’s a subtle difference when you’re typing it in, but the ramifications are large, so pay careful attention.

Q:

Q: Which of the two ways of creating a window.onload handler is better, using a function name or an anonymous function?

A:

A: One isn’t better than the other, they both do basically the same thing: set the value of window.onload to a function that will run when the page has loaded. If you need to call init from another function later in your program for some reason, then you’ll need to define an init function. Otherwise, it doesn’t matter which way you do it.

Q:

Q: What’s the difference between built-in objects like window and document, and the ones we make?

A:

A: One difference is that built-in objects follow the guidelines set by specifications, so you can refer to the W3C specifications to understand all their properties and methods. In addition, many of the built-in objects, like String, may have properties that are immutable and can not be changed. Other than that, objects are objects. The nice thing about built-in objects is they’re already built for you.

Note

Yes, String is an object! Check out a good JavaScript reference to get all the details of its properties and methods.

Bullet Points

To create a function, use the function keyword with parentheses to hold parameters, if there are any.

Functions can be named, or be anonymous.

Naming rules for functions are the same as naming rules for variables.

The body of a function goes between curly braces, and contains statements that do the work of the function.

A function can return a value with the return statement.

To invoke (or call) a function, use its name and pass any arguments it needs.

JavaScript uses pass-by-value parameter passing.

When you pass an object, like a dog, as an argument to a function, the parameter gets a copy of the reference to the object.

Variables defined in functions, including parameters, are known as local variables.

Variables defined outside of functions are known as global variables.

Local variables are not visible outside the function in which they are defined. This is known as the scope of a variable.

If you declare a local variable with the same name as a global variable, the local variable shadows the global variable.

When you link to multiple JavaScript files from your page, all the global variables are defined in the same global space.

If you assign a new variable without using the var keyword, that variable will be global, even if you are first assigning it in a function.

Functions are values that can be assigned to variables, passed to other functions, stored in arrays, and assigned to object properties.

Objects are collections of properties.

You access an object’s properties using dot notation or the [ ] notation.

If you use [ ] notation, enclose the property’s name as a string; for example, myObject[“name”].

You can change a property’s value, delete properties, or add new properties to an object.

You can enumerate an object’s properties using a for-in loop.

A function assigned to an object property is referred to as a method.

A method can use a special keyword, this, to refer to the object on which it was invoked.

A constructor is a function that makes objects.

The job of a constructor is to create a new object and initialize its properties.

To invoke a constructor to create an object, use the new keyword. For example, new Dog().

We’ve already been using several objects in this book, including document, window, and various element objects.

The window object is the global object.

The document object is one of window’s properties.

The document.getElementById method returns an element object.

HTML5cross

It’s been a whirlwind chapter of functions, objects, properties and methods—so there’s lots to make stick. Sit back, relax, and work the rest of your brain a little. Here’s your Chapter 4 crossword puzzle.

Across

Down

1.

These variables are only available in functions.

2.

This kind of function makes objects.

4.

The true global object.

3.

Functions might or might not include this kind of statement.

6.

The _________ object represents the DOM.

5.

Stringing together properties and function calls with the dot operator.

11.

Arguments are passed by ______________.

7.

We assign a handler function to this property in window.

12.

Use this keyword to start a function definition.

8.

What you supply in your function call.

14.

Functions without return statements return this.

9.

The ______ operator lets you access an object’s properties and methods.

15.

A function in an object.

10.

By convention, constructors have a name with an _________ first letter.

17.

Functions without a name.

13.

Refers to the current object in an object method.

18.

What you supply in your function definition.

16.

Variable scope that is visible everywhere.

Sharpen your pencil Solution

Use your knowledge of functions and passing arguments to parameters to evaluate the code below. After you’ve traced through the code, write the value of each variable below. Here’s our solution.

HTML5cross Solution

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training,
learning paths, books, interactive tutorials, and more.