Class

hanyoko·2023년 6월 21일
0

JAVASCRIPT

목록 보기
26/32
post-thumbnail

Class

객체 지향 프로그래밍에서 특정 객체를 생성하기 위해 변수와 메소드를 정의하는 일종의 틀
객체를 정의하기 위한 상태(멤버 변수)와 메소드(함수)로 구성된다.

템플릿
붕어빵틀 => Class

//클래스 생성
class Student{
  //생성자 - 객체의 초기화
  constructor(name, score1, score2){
    this.name = name;
    this.score1 = score1;
    this.score2 = score2;
  }
  //함수 메소드 정의
  sayHi(){
    console.log(this.name);
  }
}

//클래스 사용
let stu1 = new Student("Green", 60, 80);
let stu2 = new Student("Blue", 70, 50);

class 상속

  • 정의된 클래스를 상속 받아서 새로운 클래스를 생성할 수 있다.
  • 상속받은 부모에 해당하는 클래스에 정의된 변수, 함수 등 모든 특성을 그대로 상속받아 사용할 수 있다.
  • 자식에 해당하는 클래스에서 추가적인 부분만 정의하면 된다.
class 부모클래스 extends 클래스명{}
class Rectangle extends Person{
  // 메소드의 재정의(오버라이딩) : 필요한 함수만 재정의한다.
  // Person 함수로부터 상속(extends)받았다.
  speak(){
      console.log(`${this.name}:${this.tel}`)
    // 이 요소(Rectangle)의 name 및 tel을 출력한다.
  }
}
const rectangle = new Rectangle("yohan", 29, "010-1234-5678", true);  
//위 Rectangle에 적용될 name,age,tel,check를 입력했다.
super(부모요소 호출)
class Rectangle2 extends Person{
	constructor(name, age, tel, check){
      super(name); // 부모요소의 호출
      this.age= age; // 요소의 호출
    }
  // 상속 클래스의 생성자를 부를 때에는 반드시 super()를 호출해야한다.
}
<script>
  class Animal {
      constructor(name){
          this.name = name;
          this.speed = 0;
      }
      run(speed){
          this.speed = speed;
          console.log(`${this.name}${this.speed}로 달립니다.`);
      }
  }
  let animal1 = new Animal("동물");
  let keysArr = Object.keys(animal1);
  console.log(animal1);

  let animal2 = {
      name: "동물2",
      speed: 0,
      run: function(){
          console.log(`${this.name}${this.speed}로 달립니다.`);
      }
  }
  let keyArr2 = Object.keys(animal2);
  console.log(keyArr2);
  animal1.run(5);
  animal2.run(5);

  class Rabbit extends Animal {
      //상속 클래스의 생성자는 
      //반드시 super()를 호출해야한다 !!!!
      constructor(name, earLength){
          // this.speed = 0;
          // this.name = name;
          super(name);
          this.earLength = earLength;
      }
      hide(){
          alert(`${this.name}가 숨었습니다.`);
      }
      //오버라이딩
      //메소드 재정의
      run(speed) {
          super.run(speed);
          console.log("rabbit의 run호출")
      }
  }
  let rabbit = new Rabbit("흰 토끼");     //name, speed   run()   hide
  rabbit.run(10);
  rabbit.hide();
  </script>

은닉화

class Car{
  	#price; // price를 class 내에서만 접근 가능하게 지정했다.
      constructor(modelName, modelYear, type, price){
        this.modelName=modelName;
        this.modelYear=modelYear;
        this.type=type;
        this.price=price;
      }
      getPrice(){
        return this.price;
      }
      setPrice(price){
        this.price= price;
      }
    }
Static
		class Article{
			constructor(articleNumber) {
				this.articleNumber= articleNumber;
			}
			static printPublisher(){
				console.log(this.articleNumber);
			}
		}
		const article1= new Article(1);
		console.log(article1.articleNumber);
		// static이 붙지 않았을 경우, 함수의 요소를 호출한다.

		Article.printPublisher();
		// static이 붙었을 경우, class 명으로 호출한다.

오버라이딩

상속관계에 있는 부모 클래스에서 이미 정의된 메소드를, 자식 클래스의 메소드로 다시 재정의 하는 것

class Shape {
                constructor(width, height, color){
                    this.width = width;
                    this.height = height;
                    this.color = color;
                }
                draw(){
                    console.log(`${this.color}로 그립니다.`);
                }
                getArea(){
                    return this.width * this.height;
                }
            }
// 상속 키워드 extends
class Rectangle extends Shape {
    //메소드재정의
    //오버라이딩
    draw(){
        super.draw();
        console.log("사각형을 그립니다.");
        //자식 요소에서 메소드를 재정의 하는 것. = 오버라이딩
    }
}
class Triangle extends Shape {

}
const rectangle = new Rectangle(20,20,'blue');
rectangle.draw();
console.log(rectangle.getArea());
console.log(rectangle);
const triangle = new Triangle(20,40,"pink");

0개의 댓글