본문 바로가기
JavaScript/JavaScript

Javascript) 객체 배열-생성자 함수

by 박채니 2022. 5. 26.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


객체 배열 - 생성자 함수

관례상 대문자로 시작하는 이름을 가짐

new 연산자를 통해 호출되고, 객체를 생성

this 용법 5) 생성자 함수 안의 this는 현재 객체를 가리킴

- 화살표 함수는 생성자 함수로 사용 불가

 

HTML 코드

<button onclick="test2();">객체배열 - 생성자 함수</button>

 

Javascript 코드

const test2 = () => {
    const pets = [];
    pets.push(new Pet('뚱이', '시추', 8, 15, 'brown'));
    pets.push(new Pet('둘리', '말티즈', 6, 5, 'white'));
    pets.push(new Pet('사랑이', '코카스파니엘', 13, 3, 'white', 'brown'));
    console.log(pets);
};

function Pet(name, breed, weight, age, ...color) {
    this.name = name;
    this.breed = breed;
    this.weight = weight;
    this.age = age;
    this.color = color;
    this.bark = function() {
        return this.weight > 10 ? '왈왈' : '멍멍';
    };
};

 

현재 bark()라는 메소드가 각 객체마다 존재하는 것을 확인할 수 있습니다.

 

부모에게 bark()메소드를 한 번 정의하고 자식 객체에서 부모의 것을 끌어다가 사용한다면 훨씬 효율적일 것 같습니다.

 

Pet() 객체의 부모는 Pet() 객체를 생성할 때 자동 생성되는 Pet.prototype입니다.

function Pet(name, breed, weight, age, ...color) {
    this.name = name;
    this.breed = breed;
    this.weight = weight;
    this.age = age;
    this.color = color;
    // 객체에 직접 작성
    // this.bark = function() {
    //     return this.weight > 10 ? '왈왈' : '멍멍';
    // };
};

// Pet.prototype : 펫 객체(new Pet())의 부모 객체
Pet.prototype.bark = function() {
    return this.weight > 10 ? '왈왈' : '멍멍';
};

각 객체의 속성 중 bark() 메소드가 없어지고, prototype 객체에 링크되어있는 것을 확인할 수 있습니다.

이것을 가져와 사용하는 것이죠.

pets.forEach((pet) => {
    console.log(`${pet.name}야~ ${pet.bark()}!`);
})

pet.bark()가 잘 출력되는 것을 확인할 수 있습니다.

 

이와 같은 구조를 갖고 있으며, 현재 객체에서 없으면 부모 객체에서 찾고 부모 객체에서도 없다면 Object 객체에서 찾아 사용합니다. (prototype 체인)