• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 JavaScript, TS 게시판 지역변수와 전역변수의 차이

지역변수와 전역변수의 차이

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #38284

    김영찬
    참가자
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth - 100;
    canvas.height = window.innerHeight - 100;
    const dino = {
        x : 10,
        y : 200,
        width : 50,
        height : 50,
        draw() {
            ctx.fillstyle = 'green';
            ctx.fillRect(this.x, this.y, this.width, this.height)
        }
    }
    class Cactus {
        constructor() {
            this.x = 500;
            this.y = 200;
            this.width = 50;
            this.height = 50;
        }
        draw() {
            ctx.fillstyle = 'red';
            ctx.fillRect(this.x, this.y, this.width, this.height)
        }
    }
    
    
    function makeCactus() {
        requestAnimationFrame(makeCactus);
        let timer = 0;
        timer++;
        ctx.clearRect(0,0, canvas.width, canvas.height);
        
        if(timer % 120 === 0){
            const cactus = new Cactus();
            cactus.draw();
        }
        
        dino.draw();
    }
    
    makeCactus();
    
    
    -----------------------------
    
    자바스크립트 ES6 장애물 피하기 게음을 만들면서 질문 있습니다. makeCactus 함수에서 timer을 지역변수로 설정하면(코드 내의 굵은 글씨)
    함수 내의 timer로 이루어진 if문이 작동하지 않지만
    timer을 선생님이 강의에서 설정했듯이 전역변수로 설정하면 makerCactus 함수의 if문이 잘 작동합니다. 
    왜 그런지 알 수 있을까요???
    #38302

    codingapple
    키 마스터
    makeCactus 함수는 1초에 60번실행되어서 그런듯요
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠