It Is JS OOP and Explanation
It Is JS OOP and Explanation
A class is a blueprint or template for creating objects. It defines the characteristics and
behaviors that all objects of that class will have. A class is like a blueprint for a house. Just
as a blueprint defines the layout, dimensions, and features of a house, a class defines the
data (properties) and behavior (methods) of an object.
Properties
Properties are the attributes or data fields of an object. They represent the state of the
object. For example, a Professor class might have properties for the professor's name,
subject, and office number.
class Professor {
constructor(name, subject) {
this.name = name;
this.subject = subject;
this.officeNumber = 0;
}
}
Methods
Methods are the actions or behaviors that an object can perform. They encapsulate the code
that defines how an object interacts with the world. For example, a Professor class might
have methods for grading papers, giving lectures, and holding office hours.
class Professor {
constructor(name, subject) {
this.name = name;
this.subject = subject;
this.officeNumber = 0;
}
gradePaper(paper) {
// Grade the paper and assign a score
console.log('Grading paper...');
}
giveLecture(topic) {
// Present a lecture on the given topic
console.log(`Giving lecture on ${topic}`);
}
holdOfficeHours() {
// Meet with students during office hours
console.log('Holding office hours...');
}
}
Instances
An instance is an object that has been created from a class. It is a concrete realization of the
class's blueprint. Just as a house is a physical manifestation of a blueprint, an instance is a
physical manifestation of a class.
console.log(walsh.subject); // 'Psychology'
walsh.giveLecture('Introduction to Psychology');
console.log(lillian.subject); // 'Poetry'
lillian.holdOfficeHours();
Constructors
class Professor {
constructor(name, subject) {
this.name = name;
this.subject = subject;
this.officeNumber = 0;
}
}
Full Syntax
class ClassName {
// Properties
property1 = initial_value1;
property2 = initial_value2;
// Methods
method1(parameter1, parameter2) {
// Method body
}
method2(parameter1) {
// Method body
}
}
Here are some extra code examples to illustrate the use of classes and instances in
JavaScript:
deposit(amount) {
this.balance += amount;
}
withdraw(amount) {
this.balance -= amount;
}
getBalance() {
return this.balance;
}
}
takeExam(examName)
Sources
1. https://github.com/prabhu-sunderaraman/jan-feb-2023
2. https://github.com/usman118/typescript-projects