class person{
name;
age;
speak();
}
class Person{
//constructor
constructor(name, age) {
//fields
this.name = name;
this.age = age;
}
//methods
speak() {
console.log(`${this.name} hello!`);
}
}
const jane = new Person('jane', 20); // new 생성자로 Object 생성
console.log(jane.name); // 'jane' 출력
jane.speak(); // 'jane hello!' 출력
class User{
constructor(name, age) {
this.name = name;
this.age = age;
}
get age() {
return this.age; // age를 호출하면 바로 this.age를 반환
}
set age(value) {
this.age = value < 0 ? 0 : value;
} // 새로운 value를 받으면 this.age에 할당해줌
}
const user1 = new User('jane', 10);
console.log(user1.age);
age
는 접근자 프로퍼티.get age()
: 값 가져오기. this.age
를 사용할 때 실행되며 this.age
값을 리턴함set age(value)
: 값 설정하기. this.age
에 값을 할당할 때 실행, 매개변수로 value 받아와야함user1.age
형식으로 일반 프로퍼티에서 값에 접근하는 것과 같이 프로퍼티 값을 얻을 수 있음
❌ 에러 발생
user1객체를 만들면서 age에 값을 할당하려함 -> set age(value)를 호출
이후 삼항연산자를 거친 후 this.age에 value를 할당하려함 -> set age(value)를 호출
또 삼항연산자를 거친 후 this.age에 value를 할당하려함 -> set age(value)를 호출
console.log(user1.age);
코드로 this.age를 사용하려함 -> get age()를 호출
this.age를 리턴하려고 this.age를 사용하려함 -> get age()를 호출
또 this.age를 리턴하려고 this.age를 사용하려함 -> get age()를 호출무한반복..
class User{
constructor(name, age) {
//fields
this.name = name;
this.age = age;
}
get age() {
return this._age;
}
set age(value) {
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('jane', 10);
console.log(user1.age);
this.age
를 this._age
로 변경User
라는 class 안에는 name
, _age
총 2개의 field가 존재_age
이지만 this.age
로 호출하고 할당할 수 있는 것은 getter와 setter를 이용하기 때문!class Shape {
constructor(width, height, color){
this.width = width;
this.height = height;
this.color = color;
}
draw(){
console.log(`drawing ${this.color} color!`);
}
getArea(){
return this.width * this.height;
}
}
class Rectangle extends Shape {}
extends
키워드를 이용해서 Shape
class의 fields와 methods를 Rectangle
에 상속해줌(Rectangle
은 Shape
의 자식 class)📌 자식 class에서 필요한 부분만 재정의하기(overriding)
class Triagle extends Shape { getArea(){ return (this.width * this.height) / 2; } }
📌
super
키워드로 부모 class에 접근하기class Triagle extends Shape { draw(){ super.draw(); // Shape class의 draw 메서드를 호출 console.log('triagle!'); } }
instanceOf
왼쪽에 있는 class가 오른쪽에 있는 class의 instance인지 판별함console.log(rectangle instanceof Rectangle); // true console.log(rectangle instanceof Shape); // true console.log(rectangle instanceof Object); // true
*JS에서 만들어진 모든 class는
Object
라는 객체를 상속한 것