관리 메뉴

도드넷

JAVASCRIPT#52 - 자바스크립트 this 실전 main.js 분석1 본문

창고/JS KING 포니 [중단]

JAVASCRIPT#52 - 자바스크립트 this 실전 main.js 분석1

도드! 2016. 6. 23. 21:50
반응형



Accidentally in love...


JAVASCRIPT#52 - 자바스크립트 this 키워드와 실전 main.js 코드분석 Part1


main.js - Part 1


$(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("moseenter", 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 = "deital.html?categoryID=" + $(this).attr("categoryID") + "&itemID=" + $(this).atrr("itemID");
            $(location).attr("href", url);
        });

    this.startSlide();

}


... main.js 계속


* 빨간글씩로 표시된건 현재 공부할 분량과 현재 스크립트에서 등장하지 않는 currently missing part. 나중에 등장할걸로 예상.


Q1) arrCategory란?
- "카테고리 어레이" 일종의 배열로써,
초기화되거나 값이 아직 정해지지않았지만 이름으로 "카테고리 목록"을

담고있는 배열변수임을 짐작할수있다.


Q2) Recommend함수?

- 매우 길고 복잡한 컨스트럭터 함수. 이름이 제시하듯, "추천"칸에 관련된 함수이다. 분해해서 분석해보자. :3


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

var tmpItemList = null;
var tmpRank = null;


Recommend 함수를 위한 아트리뷰트 고유값 4개와 내부 변수 2개를 선언하고 있다.


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]);
            }
        }
    }


▲ 이중 반복문 구조로 arrCategory라는 배열에서 item값들을 빼서 tmpItemList 이라는 배열에 저장하고 있다.

동시에 tmpRank에는 tmpItemList에 저장된 아이템의 고유 아트리뷰트인 "rank값"을 저장하는데 이후 tmpRank를

검사해서 1 또는 2 또는 3이면 itemList에 해당 아이템을 itemList라는 내부 변수에 집어넣도록(push) 하고 있다.


this.showItems(this.showItemIndex);


showitems 는 아직 등장하지 않은 커스텀 함수로 현재 객체의 showItemIndex값을 파라미터로 넣어서 작동시키려 하고 있다.


var thisObj = this;


▲ 현재 함수를 사용하는 해당객체 주체를 thisObj에 저장하고 있다. 이벤트와 함께쓰이면 this가 아무리 함수객체의 내부에 쓰였더라도 항상 현재, 해당객체를 가리킬 수 없기에 저장해서 사용하고있다.


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


▲ 왼버튼을 클릭하면 move함수에 -1을 넣고 실행 오른버튼을 클릭하면 move함수에 1을 넣고 실행.


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


▲ css의 커서값을 pointer로 바꾸고 있다. recommend라는 영역에 들어가면 마우스가 클릭손가락 모양이 된다.

그런데 앞에 셀렉터 모양이 $("#recommend > div")로 조금 이상한데 대소비교 기호인 ">" 가 들어가있다.

이건 무슨뜻일까? 이건 recommend라는 id를 가진 요소 안의 하위요소중 "div"인것만 선택하라는 것이다.


$("#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 = "deital.html?categoryID=" + $(this).attr("categoryID") + "&itemID=" + $(this).atrr("itemID");
            $(location).attr("href", url);
        });


▲ 마우스를 (#recommend > div) 영역 위로 올리면(mouseenter) focused라는 클래스를 추가하고 해당객체를 주체로 해당객체를 파라미터로 전달하면서 stopSlide를 실행한다. 영역에서 마우스를 빼면(mouseleave) focused를 지우고 해당객체를 주체로 해당객체를 파라미터로 전달하면서 startSlide를 실행한다. 만약 클릭하면 해당 페이지를 url로 이동시킨다.


Q3) .siblings() 함수?

- 자신을 제외한 모든 다른 형제<li>요소들을 전부 선택하는 내장 함수. 자신을 제외한 다른 형제요소들의 하일라이트를 지우는 역할로 사용됬다. 사실 mouseleave 부분에서 지워지기하나 그냥 이중대책.


Q4) $(location).attr("href", url)란?

- 현재 페이지의 로케이션의 attribute의 href를 "url"로 바꾼다는 말.


this.startSlide();


startSlide 을 실행한다.


여기서 공부끊어야하는데, 그냥 넘어갈수없는 질문이 머릿속에 떠오른다.



this란 무엇인가?


한글로는 "각각" 혹은 "해당 객체"이 가장 적절하다고 본다. "주체"도 어울린다. 그래서 위에서 설명할때 this를 가지고

"해당객체를 주체로 해당객체를 파라미터로 전달하면서..."라고 주체주체 해당해당하면서 서술하고있다. 위에 thisObj 라는 변수를 써가면서 해당객체를 저장하는 이유도 이벤트랑 쓰면 해당객체가 이벤트를 작동시킨 객체로 변경되기 때문이 였다.


아마 Recommend 함수에서의 this는 Recommend 함수에 의해 생성된 Recommend 객체를 의미하게 될 것이다.


var pony = new Recommend(); 이런식으로 만들것이다. (참고로 함수만들때 개인적으로 선호했던

var fff = function() {} 방식이 있는데 이건 객체를 만들때 사용하는 컨스트럭터 함수로는 사용 할 수 없다. x_x)








반응형
Comments