You can create an object from the class passing arguments that are then stored inside the object.
We do so using a constructor, a special method of the class.
Here’s an example:
class Person {
constructor(name) {
this.name = name
}
}
When the object is initialized, the constructor method is called, with any parameters passed.
const flavio = new Person('Flavio')
Now we can add methods that use the name
property:
class Person {
constructor(name) {
this.name = name
}
hello() {
return 'Hello, I am ' + this.name + '.'
}
}
Notice we used this
to reference the class. This is another place where you are going to use this special JavaScript keyword, other than in object methods.
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!