Javascript - 객체생성자

YuJin Lee·2020년 10월 7일
0

Javascript

목록 보기
11/22
  • 객체생성자
    함수를 통해 새로운 객체를 만들고 넣고싶은 값 또는 함수를 구현할 수 있게 해준다.
    주로 대문자로 시작한다.
// Animal이라는 객체생성자를 만든다.
function Animal(type, name, sound) {
  // 익명 함수 - this를 사용한다.
  this.type = type;
  this.name = name;
  this.sound = sound;
  this.say = function() {
    console.log(this.sound);
  }
}

// 객체생성자를 이용해서 새로운 객체를 만들 때는 new를 앞에 붙여준다.
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say(); //멍멍
cat.say(); //야옹

  • 프로토타입(prototype)
    지정한 객체생성자 안에 키와 값을 추가해준다.
    객체생성자 함수이름.prototype.[원하는 키] = 코드
function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
}

// Animal이라는 객체생성자 안에 say라는 함수를 추가한다.
Animal.prototype.say = function() {
  console.log(this.sound);
}

// Animal이라는 객체생성자 안에 sharedValue 값을 추가한다.
Animal.prototype.sharedValue = 1;

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say(); //멍멍
cat.say(); //야옹

console.log(dog.sharedValue); //1
console.log(cat.sharedValue); //1

  • 객체생성자 상속하기
    새로운 객체생성자에서 기존 객체생성자의 기능을 재사용하고 싶을 때 사용한다.
function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
}

Animal.prototype.say = function() {
  console.log(this.sound);
};

// Dog과 Cat이라는 새로운 객체생성자를 만든다.
function Dog(name, sound) {
  //재사용 할 객체생성자.call(this, 필요한 파라미터)
  Animal.call(this, '개', name, sound);
}

function Cat(name, sound) {
  Animal.call(this, '고양이', name, sound);
}

//새로운 객체생성자의 프로토타입과 재사용할 객체생성자의 프로토타입이 같다고 선언해준다.
Dog.prototype = Animal.prototype;
Cat.prototype = Animal.prototype;

const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');

dog.say();
cat.say();



// 생성자로 객체 생성하기

function Card(suit, rank) {
  this.suit = suit;
  this.rank = rank;
}
// 생성자(Constructor)는 첫 글자를 대문자로 쓴다.

const card = new Card("하트", "A");
// 생성자로 객체를 생성할 때는 new 연산자를 사용한다.
// new 연산자로 생성한 객체를 그 생성자의 인스턴스라고 한다.

console.log(card);
// console.log(card.suit);

// var card = {};
// card.suit = "하트";
// card.rank = "A";

// console.log(card);
// 위와 같은 결과

// 생성자는 객체를 생성하고 초기화하는 역할을 한다.
// 이름은 같지만 프로퍼티 값이 다른 객체 여러개를 간단히 생성할 수 있다.

const card1 = new Card("하트", "B");
const card2 = new Card("스페이드", "2");
const card3 = new Card("클럽", "K");

console.log(card1, card2, card3);
profile
배운 것을 기록하는 곳 💻🙂

0개의 댓글