· FRONT-END/└ JS

[ JavaScript ] 내장 객체

감자도리22 2024. 5. 14. 19:07

환경 : Visual Studio Code

 

 

[ 내장 객체 ]

  • window : 자바스크립트 최상위 내장객체이며 창과 관련된 작업 처리
                    └ location : 주소, 이동과 관련된 작업을 처리
                    └ history : 방문 이력과 관련된 작업을 처리
                    └ document : 화면에 표시되는 문서에 대한 작업을 처리
  • 코드량 감소를 위해 window는 생략 가능하다

 

 [ location 객체를 콘솔 창에 찍었을 때 나오는 값에 대해 ... ]

 - 참고 : https://webzz.tistory.com/85, https://im-developer.tistory.com/219

  • location 객체 메서드 및 객체 속성
  • ancestroOrigins : 주어진 Location 객체와 연관된 document의 모든 조상 browsing context들이 역순으로 담긴 static한 DOMStringList
  • assign : 새로운 문서를 로드
    - hash : url의 해시값(#값)을 반환
    - host : url의 호스트 이름, 포트 번호를 반환
    - hostname : url에 포함된 호스트 이름을 설정하거나 반환
    - href : 주소를 설정하거나, url을 반환
    - origin : url의 프로토콜 및 호스트 정보 반환
    - pathname : url의 '/' 이후 값을 반환
    - port : url의 포트 번호 반환
    - protocol : url의 프로토콜을 반환
  • reload : 현재 문서를 새로고침
  • replace : 현재 문서를 새로운 것으로 변경
    search : 데이터 전송 방식에 관한 주소, "?(key):(value)...."형식
  • toString : 전체 url을 담고 있는 USVString을 리턴
  • valueOf
    Symbol(Symbol.toPrimitive) : 강제 타입 변환 시에 타입변환 힌트를 받아들이고, 어떤 원시 타입을 반환할 지에 대한 메서드를 정의할 수 있음

 


[ 코드 살펴보기 ] - 주석 설명 참고

전체 실행결과

 

    - window

window 객체는 자바스크립트에서 전역 객체로서, 브라우저 창이나 탭을 나타내며 다양한 속성과 메서드를 제공

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트 내장 객체</title>
    <script type="text/javascript">
        function window01() {
            // 현재 창(브라우저 탭)의 정보를 콘솔에 출력하고, 알림창을 띄웁니다.
            console.log(window);
            window.alert("알림창 테스트!");
        }

        function window02() {
            // 확인 창을 띄우고, 사용자의 선택 여부에 따라 결과를 콘솔에 출력합니다.
            var choice = window.confirm("정말로??");
            console.log(choice);
        }

        function window03() {
            // 새로운 브라우저 탭에서 주어진 주소를 엽니다.
            window.open("https://www.naver.com");
        }

        function window04() {
            // 너비와 높이가 각각 500인 팝업 창을 열고, 창의 이름을 'google'로 지정합니다.
            window.open("https://google.com", "google", "width=500, height=500");
        }

    </script>
</head>
<body>
    <div class="container w-500">
        <div class="cell center">
            <h1>자바스크립트 내장 객체</h1>
        </div>
        <div class="cell">
            <h2>창(window)</h2>
        </div>
        <div class="cell">
            <!-- 각 버튼을 클릭하면 위에서 정의한 함수가 실행됩니다. -->
            <button class="btn positive" onclick="window01();">알림창</button>
            <button class="btn positive" onclick="window02();">확인창</button>
            <button class="btn positive" onclick="window03();">bird탭</button>
            <button class="btn positive" onclick="window04();">bird창(팝업)</button>
        </div>
    </div>
</body>
</html>

 


 

   - location 

location 객체는 현재 웹 페이지의 URL과 관련된 정보를 제공하는 객체로, 이 객체를 사용하면 현재 페이지의 URL을 조작하거나, URL에 관련된 정보를 얻을 수 있음

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트 내장 객체 - location</title>
    <script type="text/javascript">
        function location01() {
            // 현재 페이지의 URL 정보를 콘솔에 출력
            // window.location과 location은 동일한 객체를 참조하므로 둘 중 아무거나 사용해도 됨
            // console.log(window.location);
            // console.log(location); //위랑 동일한 코드

            // 현재 페이지의 URL을 구글로 변경하여 이동
            location.href = "https://www.google.com";
        }

        function location02() {
            // 확인 창을 띄우고, 사용자가 확인을 누르면 네이버로 이동
            var choice = confirm("정말 이동할 거임?");
            if (choice) {
                location.href = "https://www.naver.com";
            }
        }
    </script>
</head>
<body>
    <div class="container w-500">
        <div class="cell">
            <h2>주소(location)</h2>
        </div>
        <div class="cell">
            <!-- 버튼을 클릭하면 위에서 정의한 함수가 실행됩니다. -->
            <button class="btn positive" onclick="location01();">구글로 이동</button>
            <button class="btn positive" onclick="location02();">네이버로 이동(+팝업)</button>
        </div>
    </div>
</body>
</html>

 


 

  - history

history 객체는 브라우저 창의 이동 이력을 나타내는 객체이다. 사용자가 방문한 페이지의 목록을 추적하고, 페이지를 이동하거나 되돌리는 데 사용한다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트 내장 객체 - history</title>
    <script type="text/javascript">
        function history01() {
            // window.history와 history는 동일한 객체를 참조하므로 둘 중 아무거나 사용해도 됨
            // console.log(window.history);

            // 뒤로 가기: 현재 페이지를 이전 페이지로 이동, history가 있는 경우만 작동
            // history.back(); // 이 코드 대신에 아래 코드를 사용해도 됨
            history.go(-1); // go 메서드를 사용하여 뒤로 이동하며, -1은 한 페이지 뒤로 이동을 의미(조금 더 구체적으로 작성한 것)
        }
    </script>
</head>
<body>
    <div class="container w-500">
        <div class="cell">
            <h2>이력(history)</h2>
        </div>
        <div class="cell">
            <!-- 버튼을 클릭하면 뒤로 가는 함수가 실행됩니다. -->
            <button class="btn positive" onclick="history01();">뒤로가기</button>
        </div>
    </div>
</body>
</html>

 


   - document

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트 내장 객체 - document</title>
    <script type="text/javascript">
        /*
            비교적 최신 선택 명령인 document.querySelector / All
            - CSS 선택자를 이용하여 대상을 조회할 수 있는 명령
            - 선택 대상의 개수에 따라 명령을 다르게 사용(한 개 / 여러개)
            - IE 이슈가 있으나 현재 사용해도 문제가 없음
        */
        function document01() {
            // console.log(window.document);

            //최초 1개만 선택
            // var target = document.querySelector("h3");
            // target.style.color = "blue";

            //전체선택
            var targetList = document.querySelectorAll("h3");
            //console.log(targetList);
            
            // targetList.style.color = "blue";//말도 안 되는 코드
            // targetList[0].style.color = "blue"; //말 되는 코드

            // 모든 h3 태그에 스타일을 적용합니다.
            for (var i = 0; i < targetList.length; i++) {
                targetList[i].style.color = "lightBlue";
            }
        }
        

        /*
            구버전 자바스크립트에서는 다양한 방법으로 태그를 선택했습니다.
            - getElementById()를 사용하여 아이디로 선택
            - getElementsByClassName()을 사용하여 클래스명으로 선택
            - getElementsByTagName()을 사용하여 태그명으로 선택
        */
        function document02() {
            // 아이디로 선택하는 명령 //쿼리 셀렉터에서는 #header
            // var target = document.getElementById("header");
            // target.style.backgroundColor = "yellow";

            // 클래스명으로 선택하는 명령 //쿼리 셀렉터에서는 .title
            // var targetList = document.getElementsByClassName("title");
            // for (var i = 0; i < targetList.length; i++) {
            //     targetList[i].style.backgroundColor = "yellow";
            // }

            // 태그명으로 선택하는 명령 //쿼리 셀렉터에서는 h3
            var targetList = document.getElementsByTagName("h3");

            // 모든 h3 태그에 스타일을 적용합니다.
            for (var i = 0; i < targetList.length; i++) {
                targetList[i].style.backgroundColor = "lightYellow";
            }
        }
    </script>
</head>
<body>
    <div class="container w-500">
        <div class="cell">
            <h2>문서(document)</h2>
        </div>
        <div class="cell">
            <!-- 버튼을 클릭하면 위에서 정의한 함수가 실행됩니다. -->
            <button class="btn positive" onclick="document01();">태그 선택(신)</button>
            <button class="btn positive" onclick="document02();">태그 선택(구)</button>
        </div>
        <div class="cell">
            <!-- 예시로 사용되는 h3 태그들 -->
            <h3 id="header" class="title">Hello Javascript!</h3>
            <h3 class="title">Hello Javascript!</h3>
            <h3>Hello Javascript!</h3>
        </div>
    </div>
</body>
</html>

     (+) 첫 번째 버튼은 document.querySelectordocument.querySelectorAll을 사용하여 태그를 선택

     (+) 두 번째 버튼은 구버전의 선택 방법들을 사용

 

 

 

 


[ 전체 코드 ]

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript 예제</title>

    <!-- 구글 폰트 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100..900&display=swap" rel="stylesheet">
     
    <!-- 내가 구현할 스타일 -->
    <link rel="stylesheet" type="text/css" href="../css/commons.css">
    <link rel="stylesheet" type="text/css" href="../css/test.css">
    
    <!-- font awesome 아이콘 CDN -->
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <style>

    </style>

    <!-- javascript를 의도적으로 head 자리에 배치해서 가장 먼저 실행되도록 구현 -->
    <script type="text/javascript">
        /*
            자바스크립트 내장객체
            - window : 자바스크립트 최상위 내장객체이며 창과 관련된 작업 처리
                └ location : 주소, 이동과 관련된 작업을 처리
                └ history : 방문 이력과 관련된 작업을 처리
                └ document : 화면에 표시되는 문서에 대한 작업을 처리

            (코드량 감소를 위해 window는 생략 가능하다)
        */
        function window01(){
            console.log(window);
            window.alert("알림창 테스트!");
        }
        function window02(){
            var choice = window.confirm("정말로??");
            console.log(choice);
        }
        function window03(){
            window.open("https://www.naver.com");
        }
        function window04() {
            //window.open(표시할 주소, 창이름, 창속성);
            window.open("https://google.com", "google", "width=500, height=500");
        }

        function location01(){
            //console.log(window.location);
            //console.log(location); //위랑 동일한 코드

            location.href = "https://www.google.com";
        }
        function location02(){
            var choice = confirm("정말 이동할 거임?");
            if(choice) {
                location.href = "https://www.naver.com";
            }
        }

        function history01(){
            //console.log(window.history);
            //history.back(); //history가 있는 경우에만 작용
            history.go(-1); //조금 더 자세하게 작성 (뒤로 딱 한 페이지만 이동하도록)
        }

        /*
            비교적 최신 선택 명령인 document.querySelector / All
            - CSS 선택자를 이용하여 대상을 조회할 수 있는 명령
            - 선택 대상의 개수에 따라 명령을 다르게 사용(한 개 / 여러개)
            - IE 이슈가 있으나 현재 사용해도 문제가 없음
        */
        function document01(){
            // console.log(window.document);

            //최초 1개만 선택
            // var target = document.querySelector("h3");
            // target.style.color = "blue";

            //전체선택
            var targetList = document.querySelectorAll("h3");
            //console.log(targetList);

            // targetList.style.color = "blue";//말도 안 되는 코드
            // targetList[0].style.color = "blue"; //말 되는 코드

            for(var i=0; i <targetList.length; i++) {
                targetList[i].style.color = "lightBlue";
            }
        }
        /*
            구버전 자바스크립트에서 태그를 선택하는 명령은 매우 다양했다
            - 아이디로 선택하는 명령 : getElementById()
            - 태그명으로 선택하는 명령
            - 클래스명으로 선택하는 명령
        */
        function document02(){
            //쿼리 셀렉터에서는 #header
            // var target = document.getElementById("header");
            // target.style.backgroundColor = "yellow";

            //쿼리 셀렉터에서는 .title
            // var targetList = document.getElementsByClassName("title"); //배열이 온다
            // for(var i=0; i<targetList.length; i++){
                // targetList[i].style.backgroundColor = "yellow";
            // }

            //쿼리 셀렉터에서는 h3
            var targetList = document.getElementsByTagName("h3");
            for(var i=0; i < targetList.length; i++) {
                targetList[i].style.backgroundColor = "lightYellow";
            }
        }
    </script>
</head>
<body>

    <div class="container w-500">
        <div class="cell center">
            <h1>자바스크립트 내장 객체</h1>
        </div>
        <div class="cell">
            <h2>창(window)</h2>
        </div>
        <div class="cell">
            <button class="btn positive" onclick="window01();">알림창</button>
            <button class="btn positive" onclick="window02();">확인창</button>
            <button class="btn positive" onclick="window03();">bird탭</button>
            <button class="btn positive" onclick="window04();">bird창(팝업)</button>
        </div>

        <div class="cell">
            <h2>주소(location)</h2>
        </div>
        <div class="cell">
            <button class="btn positive" onclick="location01();">구글로 이동</button>
            <button class="btn positive" onclick="location02();">네이버로 이동(+팝업)</button>
        </div>

        <div class="cell">
            <h2>이력(history)</h2>
        </div>
        <div class="cell">
            <button class="btn positive" onclick="history01();">뒤로가기</button>
        </div>


        <div class="cell">
            <h2>문서(document)</h2>
        </div>
        <div class="cell">
            <button class="btn positive" onclick="document01();">태그 선택(신)</button>
            <button class="btn positive" onclick="document02();">태그 선택(구)</button>
        </div>
        <div class="cell">
            <h3 id="header" class="title">Hello Javascript!</h3>
            <h3 class="title">Hello Javascript!</h3>
            <h3>Hello Javascript!</h3>
        </div>


    </div>

</body>
</html>

 

 

 

개인 공부 기록용입니다:)

728x90