JavaScript에서는 {}를 사용해 객체를 정의
property와 method의 요소로 이루어짐
let person = {
name: "홍길동",
age: 25,
greet: function() {
console.log("안녕하세요! 저는 " + this.name + "입니다.");
}
};
위의 코드에서 person객체는 name과 age를 property로 가지고, greet을 메서드로 가진다
{}을 이용한다let car = {
brand: "Hyundai",
model: "Sonata",
year: 2021
};
new Object()let car = new Object();
car.brand = "Hyundai";
car.model = "Sonata";
car.year = 2021;``
this을 사용해 속성을 결정하고 생성자함수는 대문자로 시작function Car(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
let myCar = new Car("Hyundai", "Sonata", 2021);
console.log(myCar); // 출력: { brand: "Hyundai", model: "Sonata", year: 2021 }
class키워드 이용해서 클래스를 정의/생성한다constructor함수를 이용해 생성자를 정의한다 <- 이 부분은 좀 특이함class Car {
constructor(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
getInfo() {
return ${this.brand} ${this.model}, ${this.year};
}
}
let myCar = new Car("Hyundai", "Sonata", 2021);
console.log(myCar.getInfo()); // 출력: "Hyundai Sonata, 2021"