Complete the code to create a simple object using a class.
class Person { constructor(name) { this.name = [1]; } } const p = new Person('Alice'); console.log(p.name);
The constructor receives a parameter name. To assign it to the object property, we use this.name = name.
Complete the code to add a method that returns a greeting.
class Person { constructor(name) { this.name = name; } greet() { return 'Hello, ' + [1] + '!'; } } const p = new Person('Bob'); console.log(p.greet());
The method accesses the object's property using this.name to get the name.
Fix the error in the class method to correctly access the property.
class Car { constructor(model) { this.model = model; } showModel() { console.log([1]); } } const c = new Car('Tesla'); c.showModel();
To access the object's property inside a method, use this.model.
Fill both blanks to create a class with a method that updates and returns the age.
class Animal { constructor(age) { this.age = age; } birthday() { this.age [1] 1; return this.[2]; } } const a = new Animal(3); console.log(a.birthday());
age() calls a function that does not exist.The birthday method adds 1 to this.age using += and returns the updated age property.
Fill all three blanks to create a class that stores a name, updates it, and returns a greeting.
class User { constructor([1]) { this.name = [2]; } greet() { return `Hi, [3]!`; } } const u = new User('Eve'); console.log(u.greet());
this inside the method causes undefined errors.The constructor receives name as a parameter and assigns it to this.name. The greet method returns a greeting using this.name.