JS 기초 : 프로토타입

0andme·2021년 8월 6일
0

JavaScript

목록 보기
16/16
  • 자바스크립트에는 클래스라는 개념이 없다. 대신 프로토타입(Prototype)이라는 것이 존재한다.
  • 클래스 개념이 없기 때문에 당연히 상속의 개념도 없다.
  • 최근 ES6에서는 Class 문법이 추가되었다. 하지만 문법이 추가되었다는 거지, 자바스크립트가 클래스 기반으로 바뀌었다는 것은 아니다.

◼ 생성자

  • function과 new를 통해 class를 흉내낼 수 있다.
function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
}

◻ 대문자 사용

function과의 구분을 위해 주로 대문자로 시작한다. (ex. Animal)

◻ this.을 사용해 매개 변수 저장

this.변수명=을 사용해 매개변수를 저장한다. this는 생성자 자신을 가리킨다.

◻ new를 이용해 객체 생성

new 키워드를 사용해 객체를 생성한다.

const dog = new Animal("개", "백구", "멍멍");
const cat = new Animal("고양이", "나비", "야옹");

◼ 프로토타입

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();

위의 코드를 보면, dog와 cat은 공통적으로 type, name, sound, say 4가지 요소를 갖고있다. 객체를 생성하게 되면 이 네가지 요소를 객체마다 가지게 되는데 이러한 객체가 수백, 수천개가 있다면 메모리에 남는 공간이 없을지도 모른다. 이를 prototype로 해결할 수 있다. 아래는 say함수를 prototype으로 작성한 코드다.

function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
Animal.prototype.say = function () {
    console.log(this.sound);
  };
const dog = new Animal("개", "백구", "멍멍");
const cat = new Animal("고양이", "나비", "야옹");
dog.say();
cat.say(); 

◼ 상속

call메서드를 사용하여 상속을 흉내낼 수 있다.
Animal객체를 상속받는 Dog와 Cat객체를 만들 때 call메서드를 사용한다. 또한 Dog 와 Cat 이 Animal을 프로토타입으로 갖는다는 것을 명시해야한다.

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);
}
---Dog 객체 생성자 함수 생성
function Cat(name, sound) {
  Animal.call(this, "고양이", name, sound);
}
---Cat 객체 생성자 함수 생성
Dog.prototype = Animal.prototype;
Cat.prototype = Animal.prototype;
---
  • 자식 객체생성자를 생성할때 부모 객체 생성자 명.call( this,부모 객체 생성자의 파라미터들) 을 작성하면 된다. 상속을 흉내내는 것이지만 상속에서 쓰이는 자식-부모의 개념으로 작성했다.

  • prototype을 공유해야 하기 때문에 Cat, Dog 객체 생성자 함수를 만들고 나서 prototype 값을 Animal.prototype 으로 설정한다. Dog.prototype = Animal.prototype;


클래스를 알고 있다면 프로토타입보다 더 깔끔하고 상속도 편하게 할 수 있다는 것을 알 수 있다. 다음에 클래스에 대해 알아보자

profile
개발이 하고 싶어? 정말 하고 싶긴 한거야?

0개의 댓글

Powered by GraphCDN, the GraphQL CDN