- 객체생성자
함수를 통해 새로운 객체를 만들고 넣고싶은 값 또는 함수를 구현할 수 있게 해준다.
주로 대문자로 시작한다.
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
this.say = function() {
console.log(this.sound);
}
}
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.prototype.say = function() {
console.log(this.sound);
}
Animal.prototype.sharedValue = 1;
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');
dog.say();
cat.say();
console.log(dog.sharedValue);
console.log(cat.sharedValue);
- 객체생성자 상속하기
새로운 객체생성자에서 기존 객체생성자의 기능을 재사용하고 싶을 때 사용한다.
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function() {
console.log(this.sound);
};
function Dog(name, sound) {
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;
}
const card = new Card("하트", "A");
console.log(card);
const card1 = new Card("하트", "B");
const card2 = new Card("스페이드", "2");
const card3 = new Card("클럽", "K");
console.log(card1, card2, card3);