[JavaScript][TIL] Class 키워드로 구현하는 constructor 기계 만들기

Trippy·2023년 11월 18일
2

JavaScript

목록 보기
24/28
post-thumbnail

Class 키워드로 구현하는 constructor 기계 만들기

class father {
  constructor() {
    this.name = 'Kim'
  }
}

let son = new father();

ES6 class라는 신문법으로 constructor를 만드려면 이렇게 따라치면 끝이다.

이제 new 키워드를 이용해서 방금 만든 father라는 기계에서 오브젝트를 새로 생성할 수 있게 된다.
constructor()라고 쓴 부분에 예전처럼 this.name 어쩌구 하면 새로 생성되는 오브젝트들에 값을 부여할 수 있다.


상속가능한 함수를 추가하려면 어떻게 하면 될까?

  1. 함수를 this.sayHi 이렇게 constructor 안에 추가하는 방법
  2. 기계의 prototype에 추가하는 방법

1 번

class father {
  constructor(){
    this.name = 'Kim';
    this.sayHi = function(){ console.log('hello') }
  }
}

var son = new father();

그럼 새로 생성되는 sonsayHi() 함수를 직접 가지게 되며 자유롭게 쓸 수 있다.

2 번

class father {
  constructor(){
    this.name = 'Kim';
  }
  sayHi(){ 
    console.log('hello') 
  }
}

var son = new father();

오브젝트에 함수 추가하듯 하시면 된다.
그럼 자식은 sayHi() 라고 썼을 때 부모의 prototype에 있던 sayHi()함수를 쓸 수 있다.
(혹은 그냥 부모.prototype.sayHi = function(){} 이렇게 해도 된다)


참고로 알아두는 Object.getPrototypeOf

이 함수 안에 오브젝트를 넣으면 부모 prototype을 출력해준다
이 오브젝트가 대체 누구로부터 prototype을 상속받고 있는지를 알려주는 함수이다.
__proto__라는 키워드와 비슷한 역할을 한다고 보면 된다.



constructor안에 파라미터 추가하기

ES6 방식으로 constructor 만들 때 파라미터를 추가하려면 이렇게 하면 된다.

calss father {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

let son = new father('park', 30);

이런 식으로 하면 파라미터를 넣어서 constructor를 만들 수 있다.
자식을 생성할 때 이제 파라미터 두개를 입력할 수 있게된다.



prototype 내에 함수 여러개 추가하기

class faher {
  constuctor(name, age) {
    this.name = name;
    this.age = age;
  }
  sayHi(){
    console.log('안녕');
  }
  sayHello(){
    console.log('하세요');
  }
}
let son = new father("park");

이렇게 쭉 쓰면 prototype에 sayHi, sayHello 등 여러개 함수를 동시에 넣을 수 있다.

profile
감금 당하고 개발만 하고 싶어요

0개의 댓글