Coding for Kids

Methods: Functions inside Objects

Functions can be part of objects too. When they are, we call them methods instead of functions. This change in name helps us separate main functions from those that belong to specific objects.

When would you want a function to be part of an object? Basically, when the function is something that specifically relates to the object.

Syntax:

This starts off by declaring an object. Inside of that, the property represents the name of the method (function) you're creating there.

Everything else is the same as any other function. Parameters are optional. The function can return a value but doesn't have to. It can call other functions, and so on.

Example:

We can use the functions the same way we use them elsewhere. We have to call them using parentheses (). And if we need to pass in an argument, we put that (or those) in the parentheses.

If we want Merlin to meow, we could use this.

Our cat has another property, age. As of this moment, he is cat.age years old. When he has a birthday (as with most of us), his age increases by one.

The this keyword

Coding for Kids Sidenote: Let's say you live in a house that has a den and there is a PlayStation® in the den. If you want to play a game, you have to turn on the PlayStation. If you explained that to someone while you're standing in front of it, you would say, "I have to turn this on." The PlayStation is inside the den, but you wouldn't say, "I have to turn on the den's PlayStation." Even bigger than that, you wouldn't say, "I have to turn on this house's den's PlayStation." In addition, when you say, "I have to turn this on," we know you don't mean you're turning the den on, or the house, for that matter. You're referring to the object in front of you, the PlayStation. That's all the keyword this is doing, referring to the PlayStation, in this example.

You may have noticed in the last code example with the happyBirthday() method, there was a keyword in there called this. It's an important part of an object and it can be confusing.

When you have a property inside an object that needs to look at another property inside the same object, you need to use this because it refers to the object it's already in.

So, happyBirthday is a property of cat and age is also a property of the same cat. We want happyBirthday to change the age of this cat, so we need to use this.age. It means to change the age of this object, which is our cat, whose name is "Merlin".

Confusing? Yeah, it's a little mind-boggly. It gets more difficult when you go deep into an object because this can start referring to something inside the thing you're using. There's a trick to get around that. You start with let self = this; and then use self as you go deeper.

There's a bit more complexity than what I'm showing you here. You won't need it until a bit further along in your training.

Just proving that there's a method to this madness!

—Dr. Wolf