JavaScript - 객체 지향 프로그래밍

LANA·2020년 4월 6일
0

JavaScript

목록 보기
10/21
post-thumbnail

하나의 모델이 되는 청사진(blueprint)을 만들고, 그 청사진을 바탕으로 한 객체(object)를 만드는 프로그래밍 패턴

blueprint/object = 프로그래밍의 class/instance
  • ES5 클래스는 함수로 정의할 수 있음.
function Car(brand, name, color) { // 함수 앞글자는 대문자로!
  // instance가 만들어질 때 실행되는 코드
}
  • ES6에서는 class라는 키워드를 이용해서 정의할 수도 있음.
class Car {
  constructor(brand, name, color) {
    // 인스턴스가 만들어질 때 실행되는 코드
  }
}

클래스의 Instance 만들기
- new 키워드를 통해서 만들 수 있다.

let avante  = new Car('hyundai', 'avante', 'black');
let mini    = new Car('bmw', 'mini', 'white');
let beetles = new Car('volkswagen', 'beetles', 'red'); 
//각각의 인스턴스는 Car라는 클래스의 고유한 속성과 메소드를 가짐.
// Car = Class ;
// avante, mini, beetles = instance;

속성과 메소드
클래스에 속성과 메소드를 정의하고, 인스턴스에서 이용함.

속성메소드
brand, name, color, currentFuel, maxSpeedrefuel(), setSpeed(). drive()

위와 같이, 객체지향 프로그래밍은 현실 세계를 기반으로 프로그래밍 모델을 만들 때에 유용함.

mini.color // "white"
mini.brand // "bmw"

클래스: 속성의 정의
ES5

function Car(brand, name, color) {
  this.brand = brand;
  this.name = name;
  this.color = color;
}

ES6

class Car() {
  constructor(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.color = color;
  }
}

클래스: 메소드의 정의
ES5

function Car(brand, name, color) { /*생략*/ }
Car.prototype.refuel = function() {
// 연료 공급을 구현하는 코드
}
Car.prototype.drive = function() {
// 운전을 구현하는 코드
}

ES6

class Car() {
  constructor(brand, name, color) { /* 생략 */ } 
  refuel() {}
  drive() {}
}

인스턴스에서의 사용

let avante = new Car('hyundai', 'avante', 'black')
avante.color; // 'black'
avante.drive(); // 아반떼가 운전을 시작합니다

let mini = new Car('bmw', 'mini', 'white')
mini.brand; // 'bmw'
mini.refuel(); // 미니에 연료를 공급합니다.

Car.prototype.drive = function() {
  console.log(this.brand + '출발!!!');
}
mini.drive() // mini출발!!!
avante.drive() // avante출발!!!

prototype
모델의 청사진을 만들 때 쓰는 원형 객체(original form)

Car.prototype.drive = function() {
  console.log(this.brand + '출발!!!');
}
 // Car.prototype이 prototype 객체. 여기에 속성이나 메소드 정의 가능.

constructor
인스턴스가 초기화될 때 실행하는 생성자 함수.
Array instance를 처음 만들 때 실행되는 함수.

function Car(brand, name, color) {
  this.brand = brand;
  this.name = name;
  this.color = color;
}

this
함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context (execution context)
new 키워드로 인스턴스를 생성했을 때에는, 해당 인스턴스가 바로 this의 값이 됨

function Car(brand, name, color) { 
  this.brand = brand;  // 이 예제에서 this는 avante
  this.name = name;
  this.color = color;
}

let avante = new Car('hyundai', 'avante', 'black')
avante.color; // 'black'
avante.drive(); // 아반떼가 운전을 시작합니다

우리가 배열을 정의하는 것은 Array의 인스턴스를 만들어내는 것과 동일하다.

let arr = new Arr('code', 'states' 'pre'); 
// === let arr = ['code', 'states' 'pre']
arr.length; //3
arr.push('course'); // 문법적으로 정확히 동일함.
  • Q. mdn 메소드 설명에 prototype이라고 붙어있는 이유?
    A. push 구현이 원형 객체에 정의되어 있기 때문
profile
Let's code like chord !

0개의 댓글