Javascript의 prototype 정리

소윤호·2021년 5월 19일
0
post-thumbnail

Javascript의 prototype 정리

안녕하세요 TriplexLab입니다.

오늘은 Javascript의 prototype 관해서 살펴보도록 하겠습니다.

Javascript가 2015부터 class문법이 추가되면서 class문법 관해서 많은 공부를 하다가, 계념이 어느 정도 잡폈을때즘
Javascript의 prototype라는 문법도 있다라는 사실을 뒤늦게 알게 되었습니다.
(햔 3년전즘인가 Javascript는 prototype 기반의 언어다 라고 들은 기억이 있긴 하는데... 그땐 필요성은 못 느끼고, 이해하기 힘들어서 그냥 넘어간 것 같네요...)

그래서 최근에 class(객체)기반의 패러다임이 이해가 어느 정도 되니깐, 저절로 prototype 쪽도 이해가 되는 것 같습니다.
지금까지 직접 코드를 작성하고, 간단한것을 만들어 보면서 느낀 것은 코드의 가독성이 나쁘지 않다고 느낍니다.
(참고로 class와, prototype는 결국 OOP 계념으로 같은거다라고 보면 됩니다.)

Javascript (ES6+)를 못쓰는 환경일 때 prototype를 사용하면 될 것 같네요.
(다양한 프로젝트를 접하다보면 최신 문법보단, 옛날 문법 기반으로 만들어진 프로젝트를 운영해야 할 때도 있으니깐요.)

(uicommon.js)

export default function Uicommon(el, objects){
    this._el = el;
    this.objs = objects;
    this.eventClick = this.objs.eventClick.bind(this)
    this.currentItem;   // 활성화 시킨애
    this.accreation = this._el;
    this.events();
}


/** 캡슐화 */
Uicommon.prototype = { 
    get accreation(){
        return this._el;
    },

    set accreation(value){
        if(typeof value !== 'string'){
            console.error('문자열 타입만 작성할수 있습니다.');
        }
        this._el = value
    },
};

/** 이벤트의 메소드 */
Uicommon.prototype.events = function() {
    const el = this._el;
    const cur = document.querySelector(el);
    cur.addEventListener('click', (e) => {
        e.preventDefault(); e.stopPropagation();
        this.eventClick(e);
    });
}

/** show의 기본 메소드 */
Uicommon.prototype.show = function() {
    ele.style.display = 'block';
};

/** hide의 기본 메소드 */
Uicommon.prototype.hide = function() {
    ele.style.display = 'none';
};

/** add(추가)의 기본 메소드 */
Uicommon.prototype.add = function(ele, color){
    ele.classList.add('active');
    this.currentItem = ele;
};

/** remove(삭제)의 기본 메소드 */
Uicommon.prototype.remove = function(ele){
    ele.classList.remove('active');
};

/** colorSet의 기본 메소드 */
Uicommon.prototype.colorSet = function(ele, color) {
    ele.style.color = color;
};

/** 스크롤 이벤트 정의 메서드, 위치값이 해당되는 컨텐츠에 왔을때 발생한다. */
Uicommon.prototype.activeScroll = function(ele){    
    var scrollTop = $(window).scrollTop();  
    ele.each(function(){
        if(scrollTop >= $(this).position().top){
            var content = $(this).find('.vertical-center');
            gsap.to(content, {duration:0.5, top: 0, opacity: 1})
        }
    });
};

(index.js)

import Uicommon from './uicommon.js'

(function() {
   new Uicommon('.list', {
        eventClick(e) {
            const targetElem = e.target;  //클릭한 대상자
            console.log(this)
            console.log(targetElem)

            this.currentItem && this.remove(this.currentItem);
            this.add(targetElem,'blue'); 
        },
    });
})();

(index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Javascript의 prototype 정리</title>
    <style>
        .active {color: blueviolet;}
    </style>
</head>
<body>
    <div class="list">
        <ul>
            <li class="li">1</li>
            <li class="li">2</li>
            <li class="li">3</li>
        </ul>
    </div>

    <script type="module" src="./js/index.js"></script>
</body>
</html>

여기까지 작업한 것을 한번 정리해 봤습니다.
위에 글은 제가 개인 블로그에도 같은 내용을 작성했습니다.
더 많은 컨텐츠 내용이 궁금하시면 오셔서 구경하세요~

TriplexLab Bolg

profile
javascript ES6+를 사랑하는 FE개발자 입니다.

0개의 댓글