Learn
In the last exercise, you created a class called Dog
, and used it to produce a Dog
object.
Although you may see similarities between class and object syntax, there is one important method that sets them apart. It’s called the constructor method. JavaScript calls the constructor()
method every time it creates a new instance of a class.
class Dog { constructor(name) { this.name = name; this.behavior = 0; } }
Dog
is the name of our class. By convention, we capitalize and CamelCase class names.- JavaScript will invoke the
constructor()
method every time we create a new instance of ourDog
class. - This
constructor()
method accepts one argument,name
. - Inside of the
constructor()
method, we use thethis
keyword. In the context of a class,this
refers to an instance of that class. In theDog
class, we usethis
to set the value of the Dog instance’sname
property to thename
argument. - Under
this.name
, we create a property calledbehavior
, which will keep track of the number of times a dog misbehaves. Thebehavior
property is always initialized to zero.
In the next exercise, you will learn how to create Dog
instances.
Instructions
1.
Create an empty class named Surgeon
.
2.
Inside the Surgeon
class, create a constructor()
method that accepts two parameters: name
and department
.
3.
Inside the Surgeon
constructor()
, create name
and department
properties and set them equal to your input parameters.
Take this course for free
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.