Javascript class syntax
Created By: chatGPT
JavaScript introduced class syntax in ES6, allowing for a cleaner and more readable way to create objects and handle inheritance. Using the class keyword, you can define a new class which encapsulates properties and methods. Here’s a basic example of a class definition:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
To create an instance of the class, you can use the new keyword. For example, you can create an instance of the Animal class and call its method like this:
const dog = new Animal('Dog');
dog.speak(); // Output: Dog makes a noise.
You can also create subclasses by extending a parent class using the extends keyword. This allows you to inherit properties and methods from another class. Here is how to create a subclass:
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
Now when you create an instance of the Dog class, it will have its own implementation of the speak method that overrides the parent class's method:
const dog = new Dog('Rex');
dog.speak(); // Output: Rex barks.
Additionally, static methods can be defined within a class. These methods belong to the class itself rather than any object instances. Here’s an example:
In conclusion, JavaScript class syntax offers a powerful way to structure your code, promoting clarity and reuse through encapsulation and inheritance. Remember to take advantage of static methods and properties, which can help keep your code organized and efficient.class MathUtil {
static add(a, b) {
return a + b;
}
}
console.log(MathUtil.add(5, 10)); // Output: 15