관리 메뉴

도드넷

JAVASCRIPT#53 - 자바스크립트 prototype이란? main.js 분석2 본문

창고/JS KING 포니 [중단]

JAVASCRIPT#53 - 자바스크립트 prototype이란? main.js 분석2

도드! 2016. 6. 24. 20:02
반응형



Pony is what i want. Pony, what i want to be. Pony, who i want to love


JAVASCRIPT#53 - 자바스크립트 prototype이란? main.js 분석2


1. 계속되는 main.js 분석


$(document).ready(function()
{
    DataMgr.loadAllCategory(completeCallback);
});

var completeCallback = function(data)
{
    var categoryDiv = new CategoryDiv(data);
    var recommend = new Recommend(data);
}

function Recommend(arrCategory)
{
    this.itemList = new Array();
    this.maxIndex = arrCategory.Length*3 - 1;
    this.showItemIndex = 0;
    this.timer = null;

    var tmpItemList = null;
    var tmpRank = null;

    for(var i = 0; i<arrCategory.length; i++)
    {
        tmpItemList = arrCategory[i].item;
        for(var j=0; j<tmpItemList.length; j++)
        {
            tmpRank = tmpItemList[j].rank;
            if(tmpRank == 1 || tmpRank == 2 || tmpRank ==3)
            {
                this.itemList.push(tmpItemList[j]);
            }
        }
    }
   
    this.showItems(this.showItemIndex);

    var thisObj = this;

    $("#leftBt").bind("click", function(){thisObj.move(-1);});
    $("#rightBt").bind("click", function(){thisObj.move(1);});

    $("#recommend > div").css("cursor", "pointer");

    $("#recommend > div").on("mouseenter", function()
        {
            $(this).addClass("focused").siblings().removeClass("focused");
            thisObj.stopSlide(thisObj);
        });
    $("#recommend > div").on("mouseleave", function()
        {
            $(this).removeClass("focused");
            thisObj.startSlide(thisObj);
        });

    $("#recommend > div").on("click", function(event)
        {
            var url = "detial.html?categoryID=" + $(this).attr("categoryID") + "&itemID=" + $(this).atrr("itemID");
            $(location).attr("href", url);
        });

    this.startSlide();
}


/*------------------ 여기까지 전에 공부했던 부분-------------------*/


Recommend.prototype.showItems = function(itemIndex)
{
    var index = null;
    for(var i=0; i<4; i++)
    {
        index = itemIndex + i;
        if(index > this.maxIndex)
        {
            index = index - (this.maxIndex+1);
        }
        $("#item"+i).text(this.itemList[index].title);
        $("#item"+i).attr("categoryID", this.itemList[index].categoryID);
        $("#item"+i).attr("itemID", this.itemList[index].id)
    }
}


Recommend.prototype.move = function(direction)
{
    if(direction == 1)
    {
        this.showItemIndex++;
        if(this.showItemIndex > this.maxIndex)
        {
            this.showItemIndex = 0;
        }
        this.showItems(this.showItemIndex);
    }

    else if(direction == -1)
    {
        this.showItemIndex--;
        if(this.showItemIndex < 0)
        {
            this.showItemIndex = this.maxIndex;
        }
        this.showItems(this.showItemIndex);
    }

    else
    {
        alert("ERROR! : INCORRECT DIRECTION : " + direction);
    }
}


Recommend.prototype.startSlide = function(obj)
{
    obj.timer = setInterval(function(){obj.move(1);}, 2000);
}

recommend.prototype.stopSlide = function(obj)
{
    clearInterval(obj.timer);
}


function CategoryDiv(arrCategory)
{
    for(var i=0; i<arrCategory.length; i++)
    {
        $("<div class='category'></div>").appendTo("#bottom").text(arrCategory[i].name)

        .attr("id", arrCategory[i].id)
    }

    var divSize = Math.ceil(750/arrCategory.length);

    $("#bottom > div").outerWidth(divSize+"px");


    $("#bottom > div").css("cursor", "pointer");


    $("#bottom > div").on("mouseenter", function()
        {
            $(this).addClass("focused").siblings().removeClass("focused");
        });
    $("#bottom > div").on("mouseleave", function()
        {
            $(this).removeClass("focused");
        });

    $("#bottom > div").on("click", function()
    {
        var url = "list.html?categoryID=" + $(this).attr("id");
        $(location).attr("href", url);
    });
}


// main.js 끝.


Q1) prototype

- 자바스크립트 prototype 키워드의 의미는 무엇일까? 그냥 보기에 객체다음에 써서 고유값, 프로퍼티 아트리뷰트 처럼 보이기도하다. 프로토타입이란 영어단어로 "원형 원본"이라는 뜻이다. 즉, Recommend.prototypeRecommend의 원형에 접근하고 있다고 보면 된다. 


Recommend.prototype.showitems의 의미는 Recommend라는 객체의 프로토타입 원형에 접근, showitems라는 함수를 정의하고 있는것이다. 즉, Recommend 소유의 내부함수, 고유 메소드 showitems()를 정의하고 있는것이다.


Q2) itemIndex

- 파라미터 전달값을 의미한다. Recommend 함수원본에서 this.showItems(this.showItemIndex); 로 showitems라는 함수를 호출할때 this.showItemIndexitemIndex로써 전달된것이다. 의미는 아이템을 보여줄 시작 인덱스 일것이다. 이는 곧 0 부터 시작해서 우버튼클릭 좌버튼클릭으로 증가하고 감소하게 된다.


Q3) $("#item"+i)

- 셀렉터인데 for반복문의 반복용변수 i가 더해지고 있다. 이건 어떻게 봐야할까?

다음은 위의 main.js와 사용되는 main.html의 일부다.


<div id="item0" class="contents">item0</div>
<div id="item1" class="contents">item1</div>
<div id="item2" class="contents">item2</div>
<div id="item3" class="contents">item3</div>


사용자가 item이라는 id뒤에 붙인 id인덱스인 0,1,2,3를 구현하고있다.


Q4) itemList

- 배열 변수로 빈배열로 선언되지만 이후 rank가 1,2,3 인 "보여질" 아이템들이 채워지게 된다.


Q5) Recommend.prototype.move

- 역시 Recommend 함수의 메소드를 정의하고있다. move 는 왼쪽버튼 오른쪽버튼을 누름에따라 전달되는 파라미터값 direction 값에 의해 showItemIndex 값을 조절한다. if 구문이 드문드문 들어있는데 이것은 인덱스가 최대혹은 최소치에 도달하면 인덱스를 리셋시키는 역할을 한다.


Q6) .startSlide .stopSlide

- 2초 자동 움직임, 자동 움직임 멈춤.


Q7) CategoryDiv 함수

- Recommend와 거의 동일한 함수로 CategoryDiv는 아이템 대신 arrCategory 카테고리 자체내용을 표기함. 또 다른점이 있다면 순위표시가 아니고 좌우버튼 표시갯수 제한이 없다는 점. 또 아래와 같은 크기 조절 메소드를 사용해서 공간을 나눠쓰게 만들어놓음


var divSize = Math.ceil(750/arrCategory.length);

$("#bottom > div").outerWidth(divSize+"px");


* 자바스크립트 ceil 메소드? : 올림 메소드

- Math.ceil(1.4) - > 결과 : 2


Q8) 객체 프로퍼티 정리

- 일단 자료 구조는 이런식임


arrCategory는 카테고리들이 들어있는 배열로 핵심 data에 속하는데 아직 실체가 들어나지 않음

각각의 원소 카테고리는 id, name, items 라는 3가지의 값을 가짐. 이중 items 또한 배열로 아이템 목록임.


items 배열 원소는 각각 categoryID, id, rank, title, info, review, QnA 라는 7가지의 값을 가짐.


Q9) this.maxIndex = arrCategory.Length*3 - 1;

- maxIndex란 무엇인가? 이건 아이템 리스트 최대 인덱스값으로 3을 곱하는 이유는 1,2,3위만 표현하기때문에

총 아이템 갯수는 카테고리의 갯수 x 3 그리고 인덱스로 처리하므로 시작수가 0 이여해서 -1을 해준것이다.


위의 코드는 카테고리별 1,2,3위를 아이템리스트에 집어놓고 이를 나열하고있는 코드이다.






반응형
Comments