TIL.64 Core J.S - 7. 클래스

Haiin·2021년 3월 19일
0

CoreJS

목록 보기
7/7
post-thumbnail

출저

  • 코어자바스크립트 - 정재남


클래스

자바스크립트는 프로토타입 기반 언어라서 클래스 및 상속 개념은 존재하지 않지만 프로토타입을 기반으로 클래스와 비슷하게 동작하게끔 하는 다양한 기법들이 도입돼 왔다. 그 후 ES6문법에 클래스가 추가되었는데 일정부분 프로토타입을 활용하고 있기 때문에 전자의 기법들을 인지하고 있는 것도 의미가 있다.

1. 클래스와 인스턴스의 개념 이해

공통된 특징을 기준으로 클래스를 정의하고, 클래스를 바탕으로 구체적인 예시, 즉 인스턴스를 만들 때 어떤 개체가 클래스의 속성을 지니게 된다.



2. 자바스크립트의 클래스

인스턴스에 상속되는지 (인스턴스가 참조하는지 === prototype) 여부에 따라 스태틱 멤버(static member) 와 인스턴스 멤버(instance member) 로 나뉜다.

let Rectangle = function (width, height) {
  this.width = width;
  this.height = height;
} // 생성자

Rectangle.prototype.getArea = function () {
  return this.width * this.height
} // 프로토타입 메서드


Rectangle.isRectangle = function (instance) {
  return instance instanceof Rectangle && instance.width > 0 && instance.height > 0;
}

let rect1 = new Rectangle(3, 4) // 인스턴스

console.log(rect1.getArea()) // 12
console.log(rect1.isRectangle(rect1)) // Error
console.log(Rectangle.isRectangle(rect1)) // true
  1. 인스턴스에서 프로토타입 메서드 에는 접근 가능
  2. 인스턴스에서 스태틱 메서드 에는 접근 불가
  3. 생성자 함수를 this로 해야만 (생성자 함수에서 호출) 가능


3. ES6의 클래스 및 클래스 상속

ES5 prototype

let ES5 = function (name) {
  this.name = name;
} 

ES5.staticMethod = function () {
  return `${this.name} staticMethod`
} 


ES5.prototype.method = function () {
  return `${this.name} method`
}

let es5Instance = new ES5('es5')

console.log(ES5.staticMethod()) // ES5 staticMethod
console.log(es5Instance.method()) // es5 method

ES6 class

let ES6 = class {
  constructor (name) {
    this.name = name;
  }
  
  static staticMethod () {
    return `${this.name} staticMethod`
  }
  
  method () {
    return `${this.name} method`
  }
  
} 

let es6Instance = new ES6('es6')

console.log(ES6.staticMethod()) // ES6 staticMethod
console.log(es6Instance.method()) // es6 method

ES6 class 상속

let Rectangle = class {
  constructor (width, height) {
     this.width = width;
     this.height = height;
  }
  getArea () {
    return this.width * this.height;
  }
};

let Square = class extends Rectangle { // 상속 관계 설정
  constructor (width) {
    super(width, width)
  }
  getArea () {
    console.log('size is :', super.getArea())
  }
}


0개의 댓글