객체

DONI·2021년 11월 14일
0

JavaScript / jQuery

목록 보기
8/18
post-thumbnail

🏹 JavaScript 객체

Java 컬렉션의 Map 인터페이스와 비슷한 형태로, { } 내에 Key : Value 작성
  🔍 JS 객체 모양으로 작성된 문자열 → JSON (JavaScript Object Notation)
       "{K : V, K : V, K : V}"


🏹 생성자 함수

객체 생성 시 호출하는 함수로, 일반적인 함수와 다르게 new 연산자를 이용해 객체 생성
  ⭐ 생성자 함수의 함수명은 반드시 대문자로 시작 !


🚩 소스코드 - 객체 생성 방법

  • 객체 리터럴 표기법 { } 이용
const snacks = {
    const brand = "롯데";
    // 변수명과 객체 key는 서로 다른 것이기 때문에 중복되어도 문제가 없다.
  
    // 속성
    name : "포카칩", 
    brand : "오리온", 
    flavor : ["Original", "Onion"], 
    price : 1500,

    // 메서드
    cook : function() {
      alert("신선한 감자를 깨끗이 씻어낸 후 껍질째 얇게 썰어 고소하게 튀겨냄")
    },
  
    info : function() {
        console.log("과자 이름 : " + this.name);
        // * 메서드에서 동일 객체 내부의 다른 속성을 참조하려면
        //   this.속성명 으로 작성해야 한다.
    }
};
  • 생성자 함수 + new 연산자 이용
// 생성자 함수
function Student(name, age, java, db, html, css) {
  
    // 매개변수로 전달 받은 값을 객체의 속성에 대입
    this.name = name;
    this.age = age;
    this.java = java;
    this.db = db;
    this.html = html;
    this.css = css;

    // 메서드
    this.getAvg = function() {

        const sum = Number(this.java) + Number(this.db)
                     + Number(this.html) + Number(this.css);
      
        const avg = sum / 4;
        return avg.toFixed(2); // toFixed(n) 함수 : 소수점 이하 자리수 지정
    }
}

// 생성자 함수는 new 연산자와 함께 사용되어야 한다.
document.getElementById("btn").addEventListener("click", function() {
  
    // Student 생성자 함수를 이용하여 객체 생성
    const std = new Student("HARAMCO", 20, 83.7, 91.3, 75.2, 67.3);

    // 만약 생성자 함수가 없을 경우
    // 객체 생성 시마다 중복되는 코드를 계속 작성해야 한다.
    /*
    const std1 = {
        name : "HARAMCO",
        age : 20,
        java : 83.7,
        db = 91.3,
        html = 75.2, 
        css = 67.3,
        getAvg : function() {
            const sum = this.java + this.db + this.html + this.css;
            const avg = sum / 4;
            return avg.toFixed(2);
        }
    }
    */

    console.log("평균 점수 : " + std.getAvg());
});
profile
틀린 내용이 있다면 댓글 또는 이메일로 알려주세요 ❤ꔛ❜

0개의 댓글