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.
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.
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.
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.