Object-oriented programming (OOP) is a programming paradigm that uses objects to represent and manipulate data. JavaScript is a versatile programming language that supports OOP concepts like inheritance, encapsulation, and polymorphism.
Here is an example of how to create a class and objects in JavaScript:
javascript
// Define a class called "Person"
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// Define a method of the class
introduce() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// Create an object of the Person class
const john = new Person("John", 30);
// Call the method of the object
john.introduce(); // Output: "Hello, my name is John and I am 30 years old."
In this example, we defined a class called "Person" with a constructor method that takes two parameters, "name" and "age". We also defined a method called "introduce" that logs a string to the console.
Then, we created an object of the "Person" class called "john" and passed in the name "John" and age "30". Finally, we called the "introduce" method on the "john" object, which logged the string "Hello, my name is John and I am 30 years old." to the console.
This is just a simple example, but it demonstrates how JavaScript can be used to implement OOP concepts.
0 Comments