Just like you can add methods to objects, you can add methods to classes.
Methods are defined in this way:
class Person {
hello() {
return 'Hello, I am Flavio'
}
}
A class method is like a function, but without the function
keyword.
We can invoke methods on an instance of the class:
class Person {
hello() {
return 'Hello, I am Flavio'
}
}
const flavio = new Person()
flavio.hello()
//Hello, I am Flavio
If you are wondering what is the difference with methods defined on object literals:
const car = {
start: function() {
console.log("Car engine started")
},
}
There’s no difference, apart from the fact that all objects instantiated from the class will inherit the method, so they don’t need to define it themselves.
Lessons in this unit:
0: | Introduction |
1: | Classes |
2: | ▶︎ Class methods |
3: | Private class properties |
4: | Constructors |
5: | Inheritance |
6: | Prototypes |
Are you intimidated by Git? Can’t figure out
merge vs rebase? Are you afraid of screwing up
something any time you have to do something in
Git? Do you rely on ChatGPT or random people’s
answer on StackOverflow to fix your problems?
Your coworkers are tired of explaining Git to
you all the time? Git is something we all need
to use, but few of us really master it. I
created this course to improve your Git (and
GitHub) knowledge at a radical level. Launching
May 21, 2024. Join the waiting list!