본문 바로가기
  • Monstera
개발공부/Javascript

[javascript] 자바스크립트 객체지향 - Object Oriented Programming(OOP)

by 네모공장장 2020. 1. 28.

객체지향


자바스크립트는 객체지향 프로그래밍  능력을 가진 언어이다.

객체지향 프로그래밍은 실제 세계에 기반한 모델을 만들기 위해 추상화를 사용하는 프로그래밍 패러다임이다. 

 

객체지향 프로그래밍은 관계성 있는 객체들의 집합이라는 관점으로 접근하는 소프트웨어 디자인으로 볼 수 있다.

각 객체는 별도의 역할이나 책임을 갖는 작은 독립적인 기계로 볼 수 있는 것이다.

 

객체지향 프로그래밍은 보다 유연하고 유지보수성이 높은 프로그래밍을 하도록 의도되었다.

또한 객체지향적인 코드는 개발을 보다 단순하게 했고, 시간이 흐른 뒤에도 보다 쉽게 이해할 수 있도록 했으며, 복잡한 상황이나 절차들을 덜 모듈화 된 프로그래밍 방법들보다 더 직접적으로 분석하고, 코딩하고, 이해할 수 있도록 만들었다.

객체지향 자바스크립트 개요 -

 

이러한 객체지향의 장점을 활용하려면 객체에 대한 이해가 있어야 한다.

아래는 생활코딩의 객체지향 프로그래밍 강의를 중심으로 공부하여 정리한 내용이다.


Chapter 01_Basic

 

객체의 기본 :

서로 연관된 변수와 함수를 그룹핑하고 이름을 붙인 것

const person = {
    firstName : '길동',
    lastName : '홍',
    fullName : function(){
        return this.firstName + this.lastName
    },
    age : 55,
    gender:'남자', 
}

person이라는 객체는 각 name, age, gender라는 key와 홍길동, 55, 남자라는 value를 가지고 있다.

하나의 쌍을 객체의 속성(property)이라고 부른다. 

* 객체의 속성이 함수이면 method라고 한다.

 

객체에 접근 :

const person = {
    name : '홍길동',
    age : 55,
    gender:'남자'
}

// .을 통해 접근
console.log('person.name', person.name); // 출력 '홍길동'
// []을 통해 접근
console.log('person['name']', person['name']); // 출력 '홍길동'

 

객체 수정 · 삭제 : 

const person = {
    name : '홍길동',
    age : 55,
    gender:'남자'
}

// 객체의 프로퍼티 수정
person.age = 80;
// 객체에 프로퍼티 추가
person.job = 'developer'

// 객체의 프로퍼티 삭제
delete person.gender;
console.log(person.gender) // 출력 undefined

객체와 반복문 : 

const person = {
    name : '홍길동',
    age : 55,
    gender:'남자'
}

for(let profile in person){
    console.log(profile, person[profile]) // 출력 name 홍길동 ...
    // !주의! person.profile은 undefined []로 속성에 접근해야한다.
}

 

this :

메소드가 자신이 속해있는 객체를 가리킴

// this를 사용하지 않은 예 (사용성이 떨어지므로 권장하지 않음)
const student1 = {
    name:'kim',
    math:50,
    english:45,
    science:30,
    sum:function(m, e, s){
        return m+e+s;
    }
}
console.log(student1.sum(kim.math, kim.english, kim.science))

// this를 사용하여 효울적으로 사용
const student2 = {
    name:'choi',
    math:45,
    english:50,
    science:35,
    sum:function(){
        return this.math + this.english + this.science;
    }
}
console.log(student2.sum())

Chapter 02_constructor

 

constructor : 

객체를 모듈화 하여 양산 및 수정이 용이하다.

// 생성자(constructor) 함수
// 일반함수와 구분하기 위하여 첫글자를 대문자로 사용
function Student(name,math,english,science){
    this.name = name;
    this.math = math;
    this.english = english;
    this.science = science;
    this.sum = function(){
        return this.math+this.english+this.science;
    }
}

const kim = new Student('kim',40,50,20);
const choi = new Student('choi',50,45,30);

console.log('kim.sum', kim.sum());
console.log('choi.sum', choi.sum());

Chapter 03_prototype

prototype: 

객체가 생성될 때마다 메서드가 생성되지 않고 한 번만 생성되기 때문에 메모리 절약, 성능 절약

메소드의 원형을 지정해 특정 객체에서 메소드를 재정의할 수 있다.

function Student(name,math,english,science){
    this.name = name;
    this.math = math;
    this.english = english;
    this.science = science;
}

Student.prototype.sum = function(){
    return this.math+this.english+this.science;
}

// kim.sum을 실행하면 해당 객체가 sum이라는 메서드를 가지고있는지 먼저 탐색한 후, 
// 있다면 객체의 sum을 실핼 (kim.sum의 경우)
// 없다면 객체의 prototype에서 sum을 탐색하여 실행 (choi.sum 의 경우)
const kim = new Student('kim',40,50,20);
// kim에서 실행되는 sum 동작을 수정 가능 
kim.sum = function(){
    return 'modify : ' + (this.math+this.english+this.science)
}

const choi = new Student('choi',50,45,30);

console.log('kim.sum', kim.sum()); // 출력 : modify 110
console.log('choi.sum', choi.sum()); // 출력 : 125

Chapter 04_class

class : 

앞서 본 constructor와 prototype을 합친 문법 설탕( : 문법을 좀 더 편하게 쓰기 위한 문법(?))

기존 문법과의 비교 ▼

 

// 기존 construtor와 prototype
function Student(name,math,english){
    this.name = name;
    this.math = math;
    this.english = english;
}

Student.prototype.sum = function(){
    return this.math+this.english;
}

const kim = new Student('kim',40,50);
kim.sum = function(){
    return 'modify : ' + (this.math+this.english)
}
const choi = new Student('choi',50,45);
// class 문법
class Student{
    constructor(name,math,english){
      this.name = name;
      this.math = math;
      this.english = english;
    }
    sum = function(){
        return this.math+this.english;
    }
}

const kim = new Student('kim',40,50);
kim.sum = function(){
    return 'modify : ' + (this.math+this.english)
}

 

상속(Inheritance) : extends

상속을 통해 공통되는 class를 바꾸지 않고, 새로운 메소드를 추가(공통되는 코드의 양을 줄이고, 유지보수성을 높인다.)

class Student{
    constructor(name,math,english){
      this.name = name;
      this.math = math;
      this.english = english;
    }
    sum = function(){
        return this.math+this.english;
    }
}
// 상속 extends
class StudentAvg extends Student{
    avg(){
        return (this.math+this.english)/2;
    }
}
const kim = new StudentAvg('kim',40,50);

super : 

상속받은 부모의 기능을 실행(중복제거) 

super() 부모의 생성자함수(constructor)를 호출

super.method()  에서의 super는 부모 class 자체

class Student{
    constructor(name,math,english){
      this.name = name;
      this.math = math;
      this.english = english;
    }
    sum = function(){
        return this.math+this.english;
    }
}

class StudentAvg extends Student{
    // Student(부모)의 constructor(생성자함수)를 호출
    super(name,math,english);
    this.science = science;
    sum(){
       // Student(부모)를  
       return super.sum() + this.science;
    }
    avg(){
        return (this.math+this.english+ this.science)/3;
    }
}
const kim = new StudentAvg('kim',40,50,45);

 

[참고] 생활코딩 youtube : JavaScript Object Oriented Programming

반응형