[TIL]201209
1. 코드스테이츠
- OOP & Inheritance Pattern 공책 정리
OOP
Computer Programming
컴퓨터 프로그램은 알고리즘의 모음이다.
언어의 3가지 타입
- Machine Language : 기계어
- Assembly Language : 기본 컴퓨터 언어를 기계어로 변역(컴퓨터계의 파파고...?)
- High-level Language : 영어와 비슷
- Procedural Language : 절차 지향적 언어, 초기 언어들이 여기에 속한다.
- Object-Oriented Languages(OOP) : 객체 지향적 언어
OOP
- 사람이 세계를 보고 이해하는 방법을 흉내낸 방법론
class & Objects
- Class : 객체를 만들기 위한 프로토타입, 붕어빵틀
Class = constructor(Properties/Attribute) + Methods/Behaviours
- Object : 클래스의 instance, 붕어빵
OOP Basic Concepts
1. Encapsulation(캡슐화)
- 객체의 속성(data fields)과 행위(메서드, methods)를 하나로 묶는다.
- 실제 구현 내용 일부를 외부에 감추어 은닉한다.
2. Inheritance(상속)
- 프로그래밍에서의 상속은 부모의 특징을 물려받는 것
- 상위 객체의 특징을 하위 객체에 넘겨주는 것
3. Abstraction(추상화)
- 내용은 복잡하지만 사용자는 쉽게 사용 사용가능.
4. Polymorphism(다형성)
- inheritance랑 연관되는 부분이 있다
- 프로그램 언어의 각 요소들(상수, 변수, 식, 오브젝트, 함수, 메소드 등)이 다양한 자료형(type)에 속하는 것이 허가되는 성질을 가리킨다.
Benefits of OOP
- Encapsulation : 복잡도를 줄이고 + 재사용성을 늘린다.
- Inheritance : 불필요한 코드를 제거한다.(똑같은 코드가 겹치지 않게 한다.)
- Abstraction : 복잡도 줄이고 + 변화의 영향을 분리한다(isolate impact of changes)
- Polymorphism : swift문구를 사용하지 않고 깨끗하게 사용가능
Inheritation Pattern
ES6 이전 Class 선언방식
1. Functional (Functional Instantiation)
- 인스턴스를 생성할 때마다 모든 메소드를 인스턴스에 할당하므로, 각각의 인스턴스들이 메소드의 수만큼 메모리를 더 차지하기 때문이다.(예시: 3개의 인스턴스, 6칸의 메모리)
const Car = function () { const someInstance = {}; someInstance.position = 0; someInstance.move = function () { this.position++; } return someInstance; } let car1 = Car(); let car2 = Car(); car1.move(); console.log(car1); // {position: 1, move: ƒ} console.log(car2); // {position: 0, move: ƒ}
2. Functional Shared
- 메소드들의 메모리 주소만을 참조하기 때문에 메모리 효율이 좋아진다.(예시: 3개의 인스턴스, 4칸의 메모리)
const extend = function(to, from) { for (let key in from) { to[key] = from[key] } }; const someMethods = {}; someMethods.move = function() { this.position++; }; const Car = function(position) { const someInstance = { position: position }; extend(someInstance, someMethods); return someInstance; } const car1 = Car(5); const car2 = Car(10); console.log(car1); // {position: 5, move: ƒ} console.log(car2); // {position: 10, move: ƒ}
3. Prototypal (Prototypal Instantiation)
- Functional Shared 방식과 비슷한 코드지만 인스턴스에 빈객체가 아니라 Object.creation(메소드)를 할당.
const someMethods = {}; someMethods.move = function() { this.position++; }; const Car = function(position) { const someInstance = Object.create(someMethods); someInstance.position = position; return someInstance; } const car1 = Car(5); const car2 = Car(10);
4. Pseudoclassical ⭐︎
- ES6 class 키워드를 이용한 방법과 내부적으로 정확히 동일한 원리로 작동
- constructor역할을 하는 함수에 this.사용, 메소드는 프로토타입으로 생성
- 찍어낼때 new operator 붙일것!
const Car = function(position) { this.position = position; }; Car.prototype.move = function() { this.position++; }; const car1 = new Car(5); const car2 = new Car(10);
Prototype Chain
- JS는 프로토타입 기반의 언어이다.
- JavaScript는 OOP를 생각하고 만든 언어가 아니고, 프로토타입기반 언어라 많은 사람들이 prototype기능을 활용해서 OOP를 구현하려고 많은 시도를 했다.
- ES6부터는 class 키워드를 통해 OOP지원 - 모든 function에는 prototype이라는 속성이 있다
용어
prototype
: 모델의 청사진을 만들 때 쓰는 원형 객체 (original form).constructor
: 생성자
- 특정 객체가 생성될 때 실행되는 코드- 인스턴스가 초기화될 때 실행하는 생성자 함수
instantiation
: 인스턴스를 생성하는 과정.__proto__
: prototype chain
- Instance.proto === Class.prototype
메소드 상속
- 객체 요소 상속의 가장 상위 단위에 Object가 있기 때문이다.
- 모든 객체는 Object를 상속받는다. - 부모객체의 prototype에 정의해 놓은 메소드들을 쓸 수 있는 이유는 상속 기능을 이용했기 때문
상속 구현
- prototype은 할당이 가능하다
-
다른 메소드를 상속받고 싶은 메소드에 상속해줄 메소드를 카피하여 할당한다.
// pseudoclassical Child.prototype = Object.create(Parent.prototype);
-
constructor는 원래 인스턴스가 가져야할(원하는 목표로) constructor로 재할당해준다.
→ 1번에서 메소드를 재할당해서 부모 constructor로 바뀐상태이기 때문에 원래의 자식 constructor로 할당해주는 단계// pseudoclassical Child.prototype.constructor = Child; Child.prototype.someMethod = function() {} // 메소드 생성 // ES6 class : extends 키워드 사용 // extends : prototype연결 & constructor연결 한번에 해결 class Child extends Parent { }
-
부모 constructor에서도 상속받아야 되기 때문에 2번에서 연결한 constructor에 call / apply를 사용하여 this값을 넣어 상속받는다.
→ this값을 넣지 않는 경우 부모 constructor의 this 값은 undefined가 된다.// pseudoclassical const Child = function (name) { Parent.call(this, name); // Parent.apply(this, arguments); } // ES6 class : super 키워드 사용 class Child extends Parent { constructor(name) { super(name); } }
Author And Source
이 문제에 관하여([TIL]201209), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@seulgea/TIL201209저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)