TIL 58 day 7장 클래스

Winney·2021년 1월 8일
1
post-thumbnail

클래스 (Class)

1. 클래스와 인스턴스

  • 클래스는 하위로 갈수록 상위 클래스 속성을 상속 + 구체적인 요건 추가 또는 변경
  • 하위 클래스가 구체와 되어도 결국 추상적인 개념
  • 인스턴스(instance) : 클래스의 속성을 지니는 실존하는 개체
  • 클래스는 다은 클래스를 상속할 수 있으나 인스턴스 생성 때 호출할 수 있는 클래스는 오직 하나이다.
  • 클래스가 정의 되어야 클래스로부터 공통적인 요소를 지니는 개체들을 생성

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

  • 자바스크립트는 프로토타입 기반 => 클래스의 개념이 존재X
  • 자바스크립트의 상속은 프로토타입 체이닝에 의한 참조
    const arr = new Array
    Array가 일종의 클래스라고 한다면 Array의 prototype 객체 내부 요소들이 인스턴스에 상속된다고 할 수 있다.
    하지만 엄연히 상속이 아닌 프로토타입 체이닝의 참조
  • Array 내부 프로퍼티들은 prototype 프로퍼티를 제외하고는 인스턴스에 상속되지 않는다.
  • 스태틱 멤버(static member)
    : 인스턴스에 상속 안 됨, 인스턴스에서 직접 접근할 수 없는 메서드
  • 인스턴스 멤버(indstance member) 또는 프로토타입 메서드(prototype method)
    : 인스턴스에 상속 됨,인스턴스에서 직접 호출 가능
    인스턴스 멤버라는 용어를 섞어쓰나 클래스 기반 언어와 다르게 자바스크립트는 인스턴스에서도 직접 메서드를 정의 할 수 있다.
    => 인스턴스 멤버라는 용어보다 프로토타입 메서드(prototype method)가 더 적절한 용어
// 생성자
var 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;
}

var rect1 = new Rectangle(3, 4)
console.log(rect1.getArea()); // 12
console.log(rect1.isRectangle(rect1)); // Type Error
console.log(Rectangle.isRectangle(rect1)); // true

3. 클래스 상속

  • 자바스크립트의 클래스 상속 구현 => 프로토타입 체이닝을 연결한 것

    클래스(prototype)이 구체적인 데이터를 지니지 않게 하는 방법 + subClass 인스턴스의 constructor가 superClass를 가리키는 것을 원래의 subClass를 바라보도록 하는 것

1) 인스턴스 생성 후 프로퍼티 제거

var extendClass1 = function(SuperClass, SubClass, subMethods) {
  SubClass.prototype = new SuperClass();
  for (var prop in Subclass.prototype) {
    if (SubClass.prototype.hasOwnProperty(prop)) {
      delete Subclass.prototype[prop];
    }
  }
  SubClass.prototype.constructor = SubClass;
  if (subMethods) {
    for (var method in subMethods) {
      SubClass.prototype[method] = subMethods[method];
    }
  }
  Object.freeze(SubClass.prototype);
  return SubClass;
}

2) 빈 함수 이용

var extendClass2 = (function() {
  var Bridge = function() {};
  return function(SuperClass, SubClass, subMethods) {
    Bridge.prototype = superClass.prototype;
    SubClass.prototype = new Bridge();
    SubClass.prototype.constructor = SubClass;
    if (subMethods) {
      for (var method in subMethods) {
        SubClass.prototype[method] = subMethods[method];
      }
    }
    Object.freeze(SubClass.prototype);
    return SubClass;
  };
})();

3) Object.create 활용

var extendClass3 = function (SuperClass, SubClass, subMethods) {
  SubClass.prototype = Object.create(SuperClass.prototype);
  SubClass.prototype.constructor = SubClass;
  if (subMethods) {
    for (var method in subMethods) {
      SubClass.prototype[method] = subMethod[method];
    }
  }
  Object.freeze(SubClass.prototype);
  return SubClass;
};

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

EX6에서 클래스 문법이 추가

1) ES5와 ES6의 클래스 문법 비교

var ES5 = function(name) {
  this.name = name;
};
ES5.staticMethod = function() {
  return this.name + ' staticMethod';
};
ES5.prototype.method = function() {
  return this.name + ' method';
};
var es5Instance = new ES5('es5');
console.log(ES5.staticMethod());
console.log(es5Instance.method());

var ES6 = class {
  constructor(name) {
    this.name = name;
  }
  static staticMethod() {
    return this.name + ' staticMethod';
  }
  method() {
    return this.name + ' method';
  }
};
var es6Instance = new ES6('es6');
console.log(ES6.staticMethod());
console.log(es6Instance.method());

2) ES6의 클래스 상속

var Rectangle = class {
  constructor (width, height) {
    this.width = width;
    this.height = height;
  }
  getArea () {
    return this.width * this.height;
  }
};
var Square = class extends Rectangle {
  constructor(width) {
    super(width, width);
  }
  getArea() {
    console.log('size is :', super.getArea());
  }
}
  • 클래스 : 어떤 사물의 공통 속성을 모아 정의한 추상적 개념
  • 인스턴스 : 클래스의 속성을 가지는 구체적 사례
  • 프로토타입 메서드 : 클래스의 prototype 내부에 정의된 메서드
  • 스태틱 메서드 : 클래스(생성자 함수)에 직접 정의한 메서드
    => 인스턴스가 직접 호출 불가.

코어자바스크립트를 다 읽었다.
처음에는 용어에 적응하느라 쉽사리 읽히 않았고 뒤로 가면 갈수록 바로 와닿는 내용은 아니라서 계속 읽었던 부분을 다시 읽고는 했다.
하지만 마지막 장을 읽었을 때의 뿌듯함이란!
이제 1회독을 했을 뿐이고 이제 막 자바스크립트의 내면을 살짝 본 느낌이다.
앞으로 자바스크립트를 계속 사용하면서 최소한 3회독은 해야지 이게 이 내용이었구나 하지 않을까 싶다. 빠른 시일 내에 책의 도움 없이 스스로 이와 같은 내용을 정리 할 수 있기를 바라며 다시 1장을 펼쳐봐야겠다.

profile
프론트엔드 엔지니어

0개의 댓글