객체 - JavaScript

Hallelujah·2024년 11월 7일

JavaScript

목록 보기
7/12

객체

JavaScript에서는 {}를 사용해 객체를 정의
property와 method의 요소로 이루어짐

  • Property : 객체가 가진 key-value 쌍
  • Method : 객체의 동작을 정의하는 함수
let person = {
    name: "홍길동",
    age: 25,
    greet: function() {
        console.log("안녕하세요! 저는 " + this.name + "입니다.");
    }
};

위의 코드에서 person객체는 nameage를 property로 가지고, greet을 메서드로 가진다

객체 생성법

  1. 객체 리터럴
    {}을 이용한다
let car = {
    brand: "Hyundai",
    model: "Sonata",
    year: 2021
};
  1. new Object()
    이것보다는 객체 리터럴을 더 많이 이용한다
let car = new Object();
car.brand = "Hyundai";
car.model = "Sonata";
car.year = 2021;``
  1. 생성자 함수
    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 }
  1. 클래스 방식
    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"
profile
개발자

0개의 댓글