Why constructors exist
Without a constructor, you create an object first and fill it in afterwards:
let dog = new Dog();
dog.name = "Rex";
dog.age = 4;
This works, but it is verbose, and it is easy to forget a line and end up with a dog that has no age. A constructor is a special method that runs automatically, once, at the moment an object is created with new. It receives the arguments you pass and sets up the object's properties, so a new object is complete from the first moment it exists.
Defining a constructor
In JavaScript the constructor is a method with the exact name constructor, written inside the class body:
class Dog {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
A class can have only one constructor. Writing two is a SyntaxError ("A class may only have one constructor"). To support optional values, use default parameters, such as constructor(name, age = 1), instead of a second constructor.
The this keyword
Inside a constructor, this refers to the object that is being created. The line this.name = name reads: set the name property on this new object to the value of the name parameter. The left side, this.name, is the property, and the right side, name, is the parameter. They only share a spelling by convention.
The this. prefix matters. Without it, the assignment changes only the parameter, which disappears when the constructor ends:
class Dog {
constructor(name, age) {
name = name; // assigns the parameter to itself
age = age;
}
}
console.log(new Dog("Rex", 4)); // Dog {}
The object comes out empty, and reading .name from it later gives undefined.
Calling the constructor
You pass the arguments to new, in the same order as the parameters:
let rex = new Dog("Rex", 4);
let luna = new Dog("Luna", 7);
When these lines finish, rex.name is already "Rex" and rex.age is 4, and the same holds for Luna with her own values. Each object gets its own copy of the properties.
Arguments follow normal JavaScript function rules. If you pass fewer than the constructor expects, the missing parameters are undefined, with no error: new Dog("Rex") gives a dog whose age is undefined. Extra arguments are ignored. A constructor can also check its inputs and throw an error when a value is not acceptable, so an invalid object is never built.
Properties that don't come from arguments
A constructor can also set properties that the caller doesn't supply. Create them inside the constructor, not outside, so that every object gets its own copy. For example, this.tricks = []; gives each dog a separate empty list. Adding "sit" to one dog's list leaves every other dog's list empty.
The exercise, step by step
- Write the constructor. Inside the
Dogclass, defineconstructor(name, age)and usethis.nameandthis.ageto store the two parameters. - Create the two dogs. Below the class, write
let rex = new Dog("Rex", 4);andlet luna = new Dog("Luna", 7);. The lines that print them are already in the starter code.
The solution in JavaScript
class Dog {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let rex = new Dog("Rex", 4);
let luna = new Dog("Luna", 7);
console.log(rex.name + " is " + rex.age);
console.log(luna.name + " is " + luna.age);
The output is:
Rex is 4
Luna is 7
Common mistakes
- Misspelling the method name. Only a method named exactly
constructoris the constructor. WritingConstructororinitcreates an ordinary method thatnewnever calls on its own. - Forgetting
this.As shown above, the properties are never set and the object stays empty. - Using the
functionkeyword. Writeconstructor(name, age) { ... }inside the class, notfunction constructor. - Passing arguments in the wrong order.
new Dog(4, "Rex")runs without any error and stores the age as the name. JavaScript does not check types, so the order is up to you. - Calling the class without
new.Dog("Rex", 4)throwsTypeError: Class constructor Dog cannot be invoked without 'new'. - Returning a value from the constructor. A constructor does not need
return. Returning an object from it replaces the onenewbuilt, which is almost never what you want, so leave it out.
Key takeaways
- The constructor is a method named
constructorthat runs automatically when you usenew. - Inside it,
thisis the new object, andthis.name = namestores a parameter as a property. - A class has at most one constructor; use default parameters for optional values.
- Missing arguments become
undefined, and nothing in JavaScript checks their types.