Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.
This Common bugs in classes and objects worksheet is part of the ACARA Digital Technologies Years 9–10 — Modular and Object-Oriented Programming (JavaScript) journey. Print it as a booklet?
Shade in the A or B circle for each question.
Draw a line connecting each item on the left to its match on the right.
| Left column | Right column | |
|---|---|---|
| 1const p = new Pet('Rex', 3); | ACreates a Pet object with new, passing the name first and the age second, in the same order as the constructor | |
| 2console.log(p.nme); | Bthis.name = name; | |
| 3Inside a constructor, this. saves a parameter as a property on the new object | CPrints undefined, because the property is called name and nme is a typo | |
| 4Arguments must be passed in the same order as the constructor parameters, for example constructor(name, age) | Dnew Pet('Rex', 3) | |
| 5const p = Pet('Rex', 3); | EThe word new is missing, so JavaScript throws the error: Class constructor Pet cannot be invoked without 'new'. | |
| 6constructor(name) { name = name; } | FThe this. is missing, so the value is never stored on the object and p.name will be undefined. |
Complete each line of code by filling in the missing parts.
Shade in the letter of the line that contains an error.
new Pet(name, age) — Common class bugs: forgetting new, leaving out this. in the constructor, swapping the arguments, or misspelling a property so it reads undefined.const pet = new Pet("Rex", 3);class Pet {
constructor(name) { this.name = name; }
}// Pet constructor(name, age)
const n = "Rex", a = 3;
const p = new Pet(n, a);// Pet sets this.name and this.age
const pet = new Pet("Rex", 3);
console.log(pet.name); constructor(name, age) {
this.name = name;
this.age = age;