prototype

jini.choi·2022년 5월 17일
0

JavaSctipt-입문

목록 보기
7/10

객체 생성자

  • 함수를 통해서 새로운 객체를 만들고 그 안에 넣고 싶은 값 또는 함수를 구현할 수 있음

  • 객체 생성자를 사용할 때는 함수의 이름을 대문자로 시작한다.

  • new키워드 사용

  • 프로토타입

  • 객체 생성자로 무언갈 만들었을 때 그걸로 만들 객체들 끼리 공유 할 수 있는 어떤 한 값이나 함수

  • 그거를 자바스크립트의 객체 생성자로 만든 함수에다가 프로토 타입으로 설정 해줄 수 있는 것

function Animal(type, name, sound){
	this.type = type;
	this.name = name;
	this.sound = sound;
}

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

//new 객체생성자이름(함수호출)
const cat = new Animal('고양이', '비키', '먀옹~');
const dog = new Animal('강아지', '재롱이', '왈왈!');

dog.say(); //"왈왈!"
cat.say(); //"먀옹~"

객체 생성자 상속하기

  • dog라는 객체 생성자 함수와 cat이라는 객체 생성자 함수를 만든다고 가정할 때 아래처럼 비슷한 내용을 입력하는 경우에 상속이라는 것을 사용해서 간단하게 할 수 있다.

상속할 시

function Animal(type, name, sound){
	this.type = type;
	this.name = name;
	this.sound = sound;
}

//prototype으로 어떤 함수를 넣어서 내부에서 this를 사용해서 각 객체가 가지고 있는 type, name, 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;

//new 객체생성자이름(함수호출)
const dog = new Dog('재롱이', '왈왈!');
const cat = new Cat('비키', '먀옹~');

dog.say(); //"왈왈!"
cat.say(); //"먀옹~"

상속 안할 시

function Dog(name, sound){
	this.type = '강아지';
	this.name = name;
	this.sound = sound; 
}
function Cat(name, sound){
	this.type = '고양이';
	this.name = name;
	this.sound = sound; 
}

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

//new 객체생성자이름(함수호출)
const dog = new Dog('재롱이', '왈왈!');
const cat = new Cat('비키', '먀옹~');

dog.say(); //"왈왈!"
cat.say(); //"먀옹~"

프로토타입의 역할

  • 어떠한 공유되는 함수와 값을 설정

객체 생성자의 역할

  • 함수를 new키워드를 사용해서 호출하게 됐을 때 어떠한 새로운 객체를 만듬

  • 그 객체 내부의 예로 type, name, sound와 같이 어떠한 값을 집어 넣을 수 있다.

  • 아니면, prototype으로 어떤 함수를 넣어서 내부에서 this를 사용해서 각 객체가 가지고 있는 type, name, sound를 조회해서 기능 구현을 할 수 있게 해준다.


이 글은 패스트캠퍼스 '프론트엔드(React)올인원패키지Online'을 수강하며 정리한 노트입니다.
https://fastcampus.co.kr/search?keyword=%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%94%EB%93%9C

profile
개발짜🏃‍♀️

0개의 댓글