JavaScript (클래스)

2023. 1. 6. 18:06개인적인 공부/프론트엔드

class

class Pesron{
	name = 'karatejin' /*Property : 클래스에 정의한 변수*/
    	call = () =>{...}  /*Method : 클래스에 정의한 함수*/
}

 

usage

const myPerson = new Person()
		myPerson.call()
    console.log(myPerson.name)

 

inheritance

class Person extends Master

 

클래스 생성 후 프린트

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

서브클래스

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

class Person extends Human{
  constructor(){
    this.name = 'karatejin'
  }
  
  printMyName(){
    console.log(this.name);
  }
}
const person = new Person();
person.printMyName();
person.printGender();

오류가 났다.

서브 클래스에서는 super 생성자를 먼저 호출하여야 한다.

 

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

class Person extends Human{
  constructor(){
    super(); /*호출*/
    this.name = 'karatejin';
  }
  
  printMyName(){
    console.log(this.name);
  }
}
const person = new Person();
person.printMyName();
person.printGender();

성별까지 나옴

class Person extends Human{
  constructor(){
    super(); // 없으면 에러 발생
    this.name = 'karatejin';
    this.gender = 'female'; // 이렇게 하면 여자
  }

'개인적인 공부 > 프론트엔드' 카테고리의 다른 글

JavaScript (Spread & Rest Operators)  (0) 2023.01.06
JavaScript (Class, Property & Methods)  (0) 2023.01.06
JavaScript ( Export & Import)  (0) 2023.01.06
JavaScript (화살표 함수)  (0) 2023.01.05
JavaScript (let 과 const)  (0) 2023.01.05