devlogs-210901

Wonseok Choi·2021년 9월 1일
0

대구AI스쿨

목록 보기
46/49

간단한 요약

객체지향 프로그래밍 (Object Oriented Programming)에 대하여 알아 보았다.


배운 내용

1. Class

  • class를 이용하여 만들어낸 것들을 instance라고 함
  • 흔한 비유: 붕어빵틀과 붕어빵 -> 붕어빵틀: Class / 붕어빵: instances
function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.fullName = function (hey) {
    console.log(`${this.firstName} ${this.lastName} ${hey}`);
  };
}
const myself = new Person('wonseok', 'choi');
myself.fullName('ya');

2. Prototype

  • 우리가 Class를 생성할 때, 동시에 자동으로 Class.prototype 객체를 생성하게 된다. 여기에 우리가 따로 method를 추가할 수 있다. 아래처럼.
  • prototype의 장점은, 각 instance가 위의 Class 내 정의된 method를 일일이 가지고 다니지 않아도 된다(메모리 절약).
  • __proto__를 통해 부모관계를 파악할 수 있다.
  • 사실 우리는 자바스크립트가 제공하는 간단한 방법을 통해 class/instance를 만들고 이용하고 있다.
    ex: array, function, object 등 등
  • 그리고 모든 위의 예시의 그 근원은 Object.prototype와 같다(object 타입의 데이터)
Person.prototype.fullName = function (hey) {
  console.log(`${this.firstName} ${this.lastName} ${hey}`);
};

3. constructor

  • 어떤 Class인지 탐색하는 property.

4. this

  • 일반함수에서의 this -> window

  • 중첩된함수에서의 this -> window

  • 이벤트에서의 this -> 이벤트 객체

  • 특정 객체 내 method에서의 this -> 그 특정 객체

  • 특정 객체 내 method 내의 함수 내 this -> window

  • 즉, 중첩으로 들어간 함수에서의 this는 늘 window 가리킴
    이 때, 내가 만약 중첩 함수 내 this가 window가 아닌 해당 object를 가리키게 하고 싶다면, 중첩된 함수 밖에서 const that = this를 만들어준다. 이 때 this는 해당 object를 가리키게 한다(관례적 해결방법).

5. template literal

  • 백틱을 이용하여 조금 더 편하게 변수를 이용하여 스트링 생성 가능

어려웠던 점

아직 완벽하게 prototype과 constructor 개념이 와닿지는 않는다. 아지만 어떤 식으로 자바스크립트가 구성되어 있는 지는 전보다 더 선명하게 이해가 된다.


나의 코드

github에 있다.

0개의 댓글