class User {
// for instance variables
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
console.log(new User("Sam", "Blue", 18));
console.log(new User("Alex", "Green", 25));
this
. (as long as they were captured in the constructor
)this
refers to the current instance of the class.this.functionName()
syntax.class Course {
constructor(name, isCompleted) {
this.name = name;
this.isCompleted = isCompleted;
}
getDescription() {
if (this.isCompleted) {
return `You have completed the ${this.name} course.`;
} else {
return `You are currently studying the ${this.name} course.`;
}
}
}
const course1 = new Course("Learn JavaScript", false);
console.log(course1.getDescription()); // "You are currently studying the Learn JavaScript course"
const course2 = new Course("Learn Programming", true);
console.log(course2.getDescription()); // "You have completed the Learn Programming course"
Object-Oriented Programming (OOP) is when you describe the real world with classes (that you can then instantiate which creates objects).
OOP 참고자료: OOP(Object-Oriented Programming, 객체 지향 프로그래밍) 이란?- hkoo9329.log
class User {
constructor(firstName, lastName, prefix, age) {
this.firstName = firstName;
this.lastName = lastName;
this.prefix = prefix;
this.age = age;
}
getFullName() {
return `${this.prefix}. ${this.firstName} ${this.lastName}`;
}
canVote() {
return this.age >= 18;
}
}
// Sample usage
const user1 = new User("Sam", "Doe", "Mrs", 20);
console.log(user1.getFullName()); // "Mrs. Sam Doe"
console.log(user1.canVote()); // true
const user2 = new User("Alex", "Green", "Mr", 17);
console.log(user2.getFullName()); // "Mr. Alex Green"
console.log(user2.canVote()); // false
const getFullName = (firstName, lastName, prefix) => {
return `${prefix}. ${firstName} ${lastName}`;
}
const canVote = (age) => {
return age >= 18;
}
// Sample usage
console.log(getFullName("Sam", "Doe", "Mrs")); // "Mrs. Sam Doe"
console.log(canVote(20)); // true
console.log(getFullName("Alex", "Green", "Mr")); // "Mr. Alex Green"
console.log(canVote(17)); // false
user1
which is an instance of the class User
.