Create a class Car with a constructor that takes make and model and a method displayInfo that logs the car’s make and model.
JavaScript uses prototypes for inheritance, but ES6 introduced the class
syntax to make working with objects and inheritance simpler and more intuitive.
A class is a blueprint for creating objects with properties and methods.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person1 = new Person("Alice", 30);
person1.greet(); // Hello, my name is Alice
Every JavaScript object has a prototype, which is another object from which it inherits methods and properties.
Before classes, this was how inheritance was handled:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person("Bob");
person1.greet(); // Hello, my name is Bob