자바스크립트 기본-클래스

뿌야·2023년 3월 16일
0

자바스크립트

목록 보기
13/24
post-thumbnail


-method: 클래스에 부착된 함수
-property: 클래스에 부착된 변수

class Person{
  constructor(){
    this.name = "Max";
  }
  printMyName(){
    console.log(this.name);
  }
}
const person = new Person();
person.printMyName();

constructor 함수로 class를 생성한 후, "new"를 이용하여 해당 class를 활용하고 있다.

더불어 class는 상속도 가능한데, 관련 코드는 다음과 같다.

class Human{
  constructor(){
    this.gender="male";
  }
  printGender(){
    console.log(this.gender);
  }
}

class Person{
  constructor(){
    super();
    this.name = "Max";
  }
  printMyName(){
    console.log(this.name);
  }
}

const person = new Person();
person.printMyName();
person.printGender();

constructor에 super()을 추가해주면 Human에 대한 내용이 상속이 가능하다

하지만 위의 복잡한 방식(ES6)은 아래(ES7)와 같이 단순화가 되었다.


constructor은 변수에 바로 할당하는 듯한 방식으로 변화하였으며,
method는 화살표 함수와 같다.

0개의 댓글