[JS] this / 동기 비동기

2022. 5. 10. 09:46·Stack/JavaScript

this

객체 프로퍼티에 할당된 함수 -> 메서드

그냥 함수는 윈도우를 바라 봄

 

let user = {

    name: 'green',

    age: 30,

    say: function(){

    console.log('aaa');

    }

}

 

let user = {

    name: 'green',

    age: 30,

    say(){

    console.log(this.name);

    }

}

 


 

08methodthis.html

<!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>
</head>
<body>
    <ul>
        <li onclick="liView(this)">menu1</li>
        <li onclick="liView(this)">menu2</li>
        <li onclick="liView(this)">menu3</li>
        <li onclick="liView(this)">menu4</li>
    </ul>
    <div><img src="../images/img_lights1.jpg" alt="안녕" onclick="imgSrc(this)"></div>

    <script>
        function imgSrc(img) {
            console.log(img.src);
        }
        function liView(a) {
            console.log(a);
        }
        let user = {
            name: 'green',
            age: 20,
            say:function() {
                console.log(this.name);
            }
        }
        let user2 = {
            name: 'blue',
            age: 30,
            say() {
                console.log(this.name);
            }
        }
        let obj = {
            print:function() {
                console.log(this);
            }
        }
        function printThis() {
            console.log(this);
        }
        printThis();
        user.say();
        user2.say();
        console.log(this);
        obj.print();
    </script>
</body>
</html>

 

08ex_t.html

<!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>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box;}
        #wrap {
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        ul {
            display: flex ;
        }
        ul li {
            width: 25%;
            list-style: none;
        }
        ul li img {
            width: 100%;
        }
        #imgView {
            position: absolute;
            width: 100%;
            height: 100vh;
            background: rgba(0, 0, 0, 0.5);
            top: 0;
            left: 0;
            display: none;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        #imgView span {
            position: absolute;
            right: 50px;
            top: 50px;
            color: #fff;
            font-size: 48px;
        }
    </style>
</head>
<body>
    <div id="wrap">
        <ul>
            <li><img src="../images/img_lights1.jpg" alt="첫번째 이미지입니다." onclick="viewImg(this)"></li>
            <li><img src="../images/img_lights2.jpg" alt="두번째 이미지입니다." onclick="viewImg(this)"></li>
            <li><img src="../images/img_lights3.jpg" alt="세번째 이미지입니다." onclick="viewImg(this)"></li>
            <li><img src="../images/img_lights4.jpg" alt="네번째 이미지입니다." onclick="viewImg(this)"></li>
        </ul>
    </div>
    <div id="imgView">
        <span onclick="hideDiv()">X</span>
        <img src="../images/img_lights1.jpg" alt="" id="bigImg">
        <p>첫번째 이미지입니다.</p>
    </div>
    <script>
        function viewImg(img) {
            let imgSrc = img.src;
            document.querySelector('#imgView').style.display = 'flex';
            document.querySelector('#bigImg').src=imgSrc;
            document.querySelector('p').innerHTML = img.alt;
        }
        function hideDiv() {
            document.querySelector('#imgView').style.display = 'none';
        }
    </script>
</body>
</html>

 

08ex.html (내가 한 것  . .)

<!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>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box;}
        img { vertical-align: top; }
        li { list-style: none; }
        .inner {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            height: 100vh;
            display: flex;
            align-items: center;
            position: relative;
            z-index: 1;
        }
        ul {
            display: flex;
        }
        img {
            width: 100%;
        }
        #blackbg {
            width: 100%;
            height: 100vh;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            display: flex;
        }
        #bigimg {
            z-index: 1;
            position: absolute;
            width: 50%;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            display: flex;
        }
        #btn {
            font-size: 62px;
            color: #fff;
            position: absolute;
            left: 80%;
            top: 5%;
            z-index: 2;
        }
    </style>
</head>
<body>
    <div id="wrap">
        <ul class="inner">
            <li><img src="../images/img_lights1.jpg" alt="첫번째 이미지입니다." onclick="imgSrc(this)"></li>
            <li><img src="../images/img_lights2.jpg" alt="두번째 이미지입니다." onclick="imgSrc(this)"></li>
            <li><img src="../images/img_lights3.jpg" alt="세번째 이미지입니다." onclick="imgSrc(this)"></li>
            <li><img src="../images/img_lights4.jpg" alt="네번째 이미지입니다." onclick="imgSrc(this)"></li>
        </ul> 
        <div id="blackbg">
            <img src="" alt="" id="bigimg">
            <div id="btn" onclick="closepic()">x</div>
        </div>
    </div>
    <script>
        function imgSrc(img) {
            alert(img.alt);

            document.querySelector('#blackbg').style.opacity = 1;
            document.querySelectorAll('img')[0].style.opacity = 0.5;
            document.querySelectorAll('img')[1].style.opacity = 0.5;
            document.querySelectorAll('img')[2].style.opacity = 0.5;
            document.querySelectorAll('img')[3].style.opacity = 0.5;

            document.querySelector('#bigimg').src = img.src;            
        }
        function closepic() {
            document.querySelector('#blackbg').style.opacity = 0;
            document.querySelectorAll('img')[0].style.opacity = 1;
            document.querySelectorAll('img')[1].style.opacity = 1;
            document.querySelectorAll('img')[2].style.opacity = 1;
            document.querySelectorAll('img')[3].style.opacity = 1;
        }
    </script> 
</body>
</html>

 


 

동기 비동기

console.log(2)

console.log(3)

console.log(4)

console.log(5)

console.log(6)

console.log(7)

for(let i = 0; i< 100; i ++) {

    console.log(i);

}

console.log(8)

 

setInterval(함수, 시간) // 시간 지나갈 때마다 함수를 실행

setInterval(function(){

    console.log('안녕');

}, 1000)  // 1000이 1초 ms 단위

 

setTimeout(함수, 시간) // 얘는 시간에 한번 때려주고 끝 ! 일회성

clearInterval(timer);   

 


 

setInterval.html

<!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>
</head>
<body>
    <script>
        setInterval(function(){
            console.log('안녕');
        },2000)
        setTimeout(function(){
            console.log('안녕');
        },5000)
        console.log(2);
    </script>
</body>
</html>

 

fadein.html

<!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>
    <style>
        * {margin: 0; padding: 0; box-sizing: border-box; }
        body {
            width: 100%;
            height: 100vh;
        }
        @keyframes fadein{
            0% { opacity: 0.4; }
            100% { opacity: 1; }
        }
        .fadeImg {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            animation: fadein 0.5s;
        }
    </style>
</head>
<body>
    <div class="fadeImg"><img src="../images/img_lights1.jpg" alt=""></div>
    <div class="fadeImg"><img src="../images/img_lights2.jpg" alt=""></div>
    <div class="fadeImg"><img src="../images/img_lights3.jpg" alt=""></div>
    <div class="fadeImg"><img src="../images/img_lights4.jpg" alt=""></div>
    <script>
        let imgDivs = document.querySelectorAll('.fadeImg');
        let indexNum = 0;
        let nextNum;

        // imgDivs 안에 있는 값 div의 스타일 display를 none으로 변경
        imgDivs.forEach(div => div.style.display = 'none');
        // for(let i=0; i<imgDivs.length; i++) {
        //     imgDivs[i].style.display = 'none';
        // }

        imgDivs[0].style.display = 'block';

        /* 
        1) 0초일 때
            indexNum = 0

        2) 3초일 때
            1번 줄 indexNum => 0 nextNum => 1
            4번 줄 indexNum => 1

        3) 6초일 때
            1번 줄 indexNum => 1 nextNum => 2
            4번 줄 indexNum => 2 
        
        4) 9초일 때
            1번 줄 indexNum => 2 nextNum => 3
            4번 줄 indexNum => 3 
        
        5) 12초일 때
            1번 줄 indexNum => 3 nextNum => 4
            4번 줄 indexNum => 
        */
        setInterval(function(){
            nextNum = indexNum === 3? 0: indexNum+1;   // nextNum = (indexNum + 1) % 4;
            imgDivs[indexNum].style.display = 'none';
            imgDivs[nextNum].style.display = 'block';
            indexNum = nextNum;
        },3000)
    </script>
</body>
</html>

 

slideLeft.html

<!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>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        li { list-style: none;}
        #divView {
            width: 600px;
            height: 400px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform:  translate(-50%, -50%);
            overflow: hidden;
        }
        #divs {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            transition: 0.5s;
        }
        .imgdiv {
            position: absolute;
            top: 0;
        }
        /* .imgdiv:nth-child(1) {
            left: 0;
        }
        .imgdiv:nth-child(2) {
            left: 100%;
        }
        .imgdiv:nth-child(3) {
            left: 200%;
        }
        .imgdiv:nth-child(4) {
            left: 300%;
        } */
    </style>
</head>
<body>
    <div id="divView">
        <div id="divs">
            <div class="imgdiv"><img src="../images/img_lights1.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights2.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights3.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights4.jpg" alt=""></div>
        </div>
    </div>
    <script>
        const imgDivs = document.querySelectorAll('.imgdiv');
        let divLeft = 0;
        imgDivs.forEach((imgdiv,index) =>{
            imgdiv.style.left = 100 * index + '%'   // imgdiv.style.left = `${index*100}%`;
        })
        // setInterval(함수, 시간)
        setInterval(function(){
            // 3초마다 이미지전환
            // dom요소divs의 left값이 0%, -100%, -200%, -300%, 0, -100% . . .
            divLeft = divLeft=== -3? 0 : divLeft - 1;
            document.querySelector('#divs').style.left = `${divLeft * 100}%`
        },3000) 
    </script>
</body>
</html>
</body>
</html>

 

slideLeft_real.html (인디게이터 추가버전)

<!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>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        li { list-style: none;}
        #divView {
            width: 600px;
            height: 400px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform:  translate(-50%, -50%);
            overflow: hidden;
        }
        #divs {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            transition: 0.5s;
        }
        .imgdiv {
            position: absolute;
            top: 0;
        }
        /* .imgdiv:nth-child(1) {
            left: 0;
        }
        .imgdiv:nth-child(2) {
            left: 100%;
        }
        .imgdiv:nth-child(3) {
            left: 200%;
        }
        .imgdiv:nth-child(4) {
            left: 300%;
        } */
        .btn {
            width: 60px;
            height: 60px;
            background-color: tomato;
            color: #fff;
            border-radius: 50%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            line-height: 60px;
        }
        #prev {
            margin-left: -250px;
        }
        #next {
            margin-left: 250px;
        }
        #indi {
            position: absolute;
            bottom: 0;
            /* background-color: lightblue; */
            width: 100%;
            text-align: center;
            padding: 10px;
        }
        #indi span {
            display: inline-block;
            width: 16px;
            height: 16px;
            background-color: tomato;
            border-radius: 50%;
            margin: 0 6px;
            font-size: 0;
        }
        #indi span.on {
            background-color: #000;

        }
    </style>
</head>
<body>
    <div id="divView">
        <div id="divs">
            <div class="imgdiv"><img src="../images/img_lights1.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights2.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights3.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights4.jpg" alt=""></div>
            <!-- <div class="imgdiv"><img src="../images/img_lights1.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights2.jpg" alt=""></div> -->
        </div>
        <div id="prev" class="btn">이전</div>
        <div id="next" class="btn">다음</div>
        <div id="indi"></div>
    </div>
    <script>
        const imgDivs = document.querySelectorAll('.imgdiv');
        const next = document.querySelector('#next');
        const prev = document.querySelector('#prev');
        const indiDiv = document.querySelector('#indi');
        let divLeft = 0;
        let current = 0;
        let indiStr = "";
        // setInterval을 담을 변수
        let timer;
        imgDivs.forEach((imgdiv,index) =>{
            imgdiv.style.left = `${index*100}%`;   // imgdiv.style.left = `${index*100}%`;
            indiStr = indiStr + `<span>${index}</span>`
        })
        indiDiv.innerHTML = indiStr;
        let indi = document.querySelectorAll('#indi span');
        indi[0].classList.add('on');
        console.log(indi);
        // 인디게이터 이벤트 연결
        indiDiv.addEventListener('click', function(e){
            let targetNum = e.target.innerHTML;
            moveDiv(targetNum);
        })
        // document.querySelector('#indi').innerHTML = indiStr;
        // 이전, 다음 버튼 이벤트 연결
        prev.addEventListener('mouseenter', function(){
            stopIt();
        })
        prev.addEventListener('mouseleave', function(){
            startIt();
        })
        prev.addEventListener('click',function(){
            // 이전으로 이동
            // 현재의 이전값을 구함
            let prevNum = current == 0? imgDivs.length-1 : current-1; // imgDivs.length-1 = 3
            moveDiv(prevNum);
        })
        next.addEventListener('mouseenter',function(){
            stopIt();
        })
        next.addEventListener('mouseleave',function(){
            startIt();
        })
        next.addEventListener('click', function(){
            //현재의 다음값을 구함
            let nextNum = current == imgDivs.length-1? 0 : current + 1;
            //다음값으로 이동
            moveDiv(nextNum);
        })
        // div를 이동시키는 함수
        function moveDiv(left){
            document.querySelector('#divs').style.left = `${-(left * 100)}%`;
            current = left;
            console.log(current);
            indi.forEach(ind=>{ind.classList.remove('on');})
            indi[current].classList.add('on');
        }
        // 현재 보고있는 div가 0일 때 이전 3 다음 1
        // 현재 보고있는 div가 1일 때 이전 0 다음 2
        // 현재 보고있는 div가 2일 때 이전 1 다음 3
        // 현재 보고있는 div가 3일 때 이전 2 다음 0
        // 자동이미지 전환 실행함수(setInterval)
        function startIt() {
             // setInterval(함수, 시간)
            timer = setInterval(function(){
            // 3초마다 이미지전환
            // dom요소divs의 left값이 0%, -100%, -200%, -300%, 0, -100% . . .
            divLeft = current === imgDivs.length-1 ? 0 : divLeft + 1;
            moveDiv(divLeft);
            },3000)
        }
        // 자동이미지 전환 멈춤함수(clearInterval)
        function stopIt() {
            clearInterval(timer);
        }
        startIt();
    </script>
</body>
</html>
</body>
</html>

'Stack > JavaScript' 카테고리의 다른 글

[JS] String Method  (0) 2022.05.12
[JS] 함수 2  (0) 2022.05.12
[JS] 농구게임 🏀  (0) 2022.05.06
[JS] 기본구문 복습 !  (0) 2022.05.06
[JS] 객체  (0) 2022.05.04
'Stack/JavaScript' 카테고리의 다른 글
  • [JS] String Method
  • [JS] 함수 2
  • [JS] 농구게임 🏀
  • [JS] 기본구문 복습 !
7ingout
7ingout
  • 7ingout
    Hello, 7ingout world!
    7ingout
  • 전체
    오늘
    어제
    • 분류 전체보기 (205)
      • Project (5)
      • Stack (173)
        • React (40)
        • JavaScript (50)
        • TypeScript (14)
        • HTML (11)
        • CSS (31)
        • Spring (9)
        • PHP (15)
        • SQL (3)
        • Python (0)
      • ETC (9)
      • Design (13)
        • Illustrator (6)
        • Photoshop (7)
      • Articloid (4)
        • 7ingout (4)
  • 공지사항

    • ☻
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
7ingout
[JS] this / 동기 비동기
상단으로

티스토리툴바