멋쟁이 사자처럼 FE 2기 - 32

임홍렬·2022년 5월 17일
0
post-thumbnail

220517


객체지향 프로그래밍


객체지향 프로그래밍이란 ?

 자바스크립트 객체는 데이터의 묶음 이라면 객체 지향의 객체는 우리가 표현하고자 하는 구체적인 사물을 추상적으로 표현한것이다.
 객체는 행동과 상태를 가지는데 행동 : 메소드, 상태 : 프로퍼티
 
//나를 개첵로 표현

const me = {
    name : '임홍렬',
    address : '경기도 고양시 00동 00로',
    phoneNum : '010-0000-0000',
    canWalk : function(){
        console.log('홍렬이가 웃는다.');
    }
}
//나에게 능력부여해주기

const me = {
    name : '임홍렬',
    address : '경기도 고양시 00동 00로',
    phoneNum : '010-0000-0000',
    canWalk : function(){
        console.log('홍렬이가 웃는다.');
    }
}
    teaching : function(student){
        student.codingskill();
    }
}
// 새로운 객체 만들기


const student = {
    level: 1,
    levelUp : function(){
        this.codingskill++;
    }
}
// 능력 향상

me.teaching(student);
  • 이처럼 객체와 객체가 서로 메소드를 통해 상호작용하게 하는것이 바로 객체지향 프로그래밍이라고 한다.

생성자 (constructor)

객체를 만들 때 new 연산자와 함께 사용하는 함수이다.
// 내장함수

let myArr = new Array(1,2,3);
// 생성자를 통해 생성된 객체는 같은 프로퍼티와 메서드를 공유할 수 있다

let myArr = new Array(1,2,3);
let myArr2 = new Array(4,5,6);

myArr2.length
myArr.length

myArr.forEach(item=>{
    console.log(item);
}) 
// 1, 2, 3

myArr2.forEach(item => {
    console.log(item);
})
// 4, 5, 6

커스텀 생성자 만들어보기

//생성자는 함수이므로 기본적을 함수가 필요하다.
//생성자 함수는 암묵적으로 대문자로 시작하는 이름을 가지는 것으로 약속되어 있다.

function Factory(){}
// new 키워드를 통해 객체를 생성

function Factory(){}
let robot1 = new Factory();
  • Factory 생성자 함수는 따로 return 값을 가지지 않지만 new키워드가 앞에 붙게되면 실행되었을 때 자동적으로 객체를 생성하고 반환한다.
    이렇게 반환되어 만들어진 객체를 다른 말로 인스턴스(instance) 라고 한다.
//생성자 함수와 객체의 관계는 instanceof 로 확인 할 수 있다.

robot1 instanceof Factory
음식 이름의 배열을 전달하면 배열안에서 랜덤하게 메뉴를 뽑아내는 로봇객체의 생성자를 만들어보기.
const foods = ['짜장면', '뽁음밥', '해장국', '치킨'];

        function FoodBot(foodNames) {
            this.menu = foodNames;
            this.sayMenu = function () {
                console.log(this.menu[Math.floor(Math.random() * this.menu.length)]);
            }
        }

const foodBotMark1 = new FoodBot(foods);

프로토타입 (prototype)

손쉽게 객체를 생산할 수 있지만, 객체의 메서드를 등록 할때마다 새로운 함수를 생성하고 있어 
이러한 자원의 낭비를 해결하기 위해 등장했다.
프로토타입은 모든 인스턴스가 하나의 메서드를 공유하도록 만들어 자원을 더 효율적으로 사용하도록 도와준다.

우리가 만들었던 음식 로봇객체의 메서드를 프로토타입으로 분리해보고, 그리고 객체의 메서드가 서로 동일한 주소를 참조하는지 확인해보기

const foods = ['짜장면', '뽁음밥', '해장국', '치킨'];

function FoodBot(foodNames) {
    this.menu = foodNames;
}

FoodBot.prototype.sayMenu = function () {
    console.log(this.menu[Math.floor(Math.random() * this.menu.length)]);
};

const foodBotMark1 = new FoodBot(foods);

우리가 객체지향 개념에서 만들었던 ‘나’ 와 ‘대상’ 객체를 생성자를 통해서 만들어 볼 수 있도록 코드를 수정해보자.

// 

// const me = {
//    name : '임홍렬',
//    address : '경기도 고양시 00동 00로',
//    phoneNum : '010-0000-0000',
//    canWalk : function(){
        console.log('홍렬이가 웃는다.');
    }
}
//    teaching : function(student){
//        student.codingskill();
    }
}

//const student = {
//    level: 1,
//    levelUp : function(){
//        this.level++;
    }
}
//        function Me(name, address, phoneNum) {
//            this.name = name;
//            this.address = address;
//            this.phoneNum = phoneNum;
        }

        Me.prototype.canWalk = function () {
            console.log('홍렬이가 웃는다.');
        }

        Me.prototype.teaching = function (student) {
            student.codingskill();
        }

        function Student(level) {
            this.level = level;
        }

        Student.prototype.codingskill = function () {
            this.level++;
        }

객체의 상속

CSS 에서 익숙하게 다루었던 상속이라는 개념이 자바스크립트에서도 존재한다.
// 부모역할을 할 생성자 함수

function Parent() {
    this.name = '홍렬';
}
Parent.prototype.rename = function (name) {
    this.name = name;
}
Parent.prototype.sayName = function () {
    console.log(this.name);
}
// 자식 역할을 할 생성자

function Child() {
    Parent.call(this);
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.canWalk = function () {
    console.log('now i can walk!!');
}
  • 위의 코드에서 call 함수는 Child 함수의 this가 Parent 생성자 함수의 this를 바라보게 만들어, Child 를 통해 생성된 인스턴스의 this 가 Parent 함수안의 프로퍼티에 접근할 수 있게한다.
  • Object.create 함수는 주어진 인자를 Child.prototype에 연결하는 역할을 한다.
    즉, Parent 객체의 프로토타입을 Child 객체의 프로토타입이 참조하게 한다.
  • 위의 두 가지 과정을 통해 Child 객체는 Parent 객체의 모든 것을 상속받게 된다.
profile
뜨내기 FE 개발자

0개의 댓글