Assignment
class 생성을 연습해보겠습니다.
MyMath 라는 class를 생성해주세요.
constructor 에서는 숫자 2개를 인자로 받아 프로퍼티로 저장합니다.
총 4개의 메서드를 구현해주세요.
getNumber : 두 개의 숫자가 무엇인지 배열로 반환하는 메서드 → ex) [1, 2]
add : 두 개의 숫자를 더하는 메서드
substract : 두 개의 숫자를 빼는 메서드
multiply : 두 개의 숫자를 곱하는 메서드
코드
class MyMath {
constructor(num1, num2) {
this.num1 = num1;
this.num2 = num2;
}
getNumber() {
return Array(this.num1, this.num2)
}
add() {
return this.num1 + this.num2
}
substract() {
return this.num1 - this.num2
}
multiply() {
return this.num1 * this.num2
}
}
const oneMath = new MyMath(2,3)
console.log(oneMath)
주의할 점
class 생성은 첫 문자는 대문자
constructor의 this 꼭 사용
-> 이유:
class를 통해 생성된 객체를 인스턴스 라고 부른니다.
인스턴스를 생성할 때마다 인자를 받을 텐데 해당 인자에 접근해야 객체를 만들 수 있으니 사용한다.
this를 빼보면 빈 객체만 나온느걸 확인 할 수 있다.
그래도 잘 모르겠으면 자바스크립트 class 공식문서를 보면 된다.
잘 모르겠으면 공식 문서에 나온 대로 사용하면 된다.
class 연습하기
class Student {
constructor (name, id,classNum) {
this.name = name,
this.id = id,
this.classNum = classNum,
this.absence = 0
}
plusAbsence() {
this.absence++;
}
}
const juno = new student('juno', 13, '2반')
console.log(juno)
juno.plusAbsence()