void 0 이란?

라이브러리 코드를 학습하던 중에 이런 코드를 발견했다. 
if(params === void 0){ }

void 0이 뭐지? 
검색해 본 결과 void는 javascript의 연산자이고 항상 undefined를 반환한다고 한다.
void 0, void 'hello' 등 전부다 undefined를 한다.

그럼 왜? undefined를 안쓰고?
if(params === undefined){ }

첫번째로는 undefined는 항상 undefined가 아닐 수도 있다는 얘기다.
var undefined = 'hello';

console.log(undefined);
// hello

그리구 짧아서 브라우저로 전송되는 바이트 수를 줄일 수 있고 관용적이라고 한다.

MDN링크

'~2022 > FE-개발 개념' 카테고리의 다른 글

CND이란?  (0) 2019.05.16
MVC 패턴  (0) 2019.05.16
CSS를 이용해 객체 가운데 위치하기!  (0) 2018.10.29
구글 API KEY생성하는 법  (0) 2018.10.26
let 키워드, const 키워드  (0) 2018.10.23
ES6 매개변수 기본 정의  (0) 2018.10.16
javascript .map() 메서드를 알아보자  (0) 2018.09.17
javascript .filter() 메서드를 알아보자.  (0) 2018.09.17

 

클릭 -> 스크롤 이동을 구현해보도록 하겠다.

scrollintoview()를 사용하면 간단하다.

 

 

HTML

<p>
  클릭하세요
  <button id="box1" type="button">box1</button>
  <button id="box2" type="button">box2</button>
  <button id="box3" type="button">box3</button>
  <button id="box4" type="button">box4</button>
  <button id="box5" type="button">box5</button>
  <button id="box6" type="button">box6</button>
  <button id="box7" type="button">box7</button>
</p>
<div class="box1">박스1입니다.</div>
<div class="box2">박스2입니다.</div>
<div class="box3">박스3입니다.</div>
<div class="box4">박스4입니다.</div>
<div class="box5">박스5입니다.</div>
<div class="box6">박스6입니다.</div>
<div class="box7">박스7입니다.</div>

클릭하여 이동할 수 있게 버튼을 만들어준다.

 

 

CSS

body,div{
  margin:0;
  padding:0;
}

div{
  display: flex;
  align-items: center;
  justify-content: center;
}

.box1{ background-color:red; }
.box2{ background-color:orange; }
.box3{ background-color:yellow; }
.box4{ background-color:green; }
.box5{ background-color:blue; }
.box6{ background-color:navy; }
.box7{ background-color:purple; }

 

 

JS

const btnArr = document.getElementsByTagName('button');

for(let i = 0; i < btnArr.length; i++){

  btnArr[i].addEventListener('click',function(e){
    e.preventDefault();
    document.querySelector('.box' + (i + 1)).scrollIntoView(true);
  });

}

 

버튼의 index를 이용해서 class를 검색하여 엘리먼트를 찾는다.

*index로 찾은 엘리먼트를 통해 scrollIntoView() 해주기 때문에 class나 id가 수정되면 스크립트 오류가난다.

 

예제

예제 버튼 클릭 시 티스토리 스크롤도 top되는 현상이 생겨버렸다.!! codePen가서 해보시길..

See the Pen scrollIntoView example by leeyoonseo (@okayoon) on CodePen.

 

크롬만 테스트했고, scrollintoview 메서드가 궁금하면 MDN을 살펴보자.

https://developer.mozilla.org/ko/docs/Web/API/Element/scrollIntoView

 

 

마우스 휠로 전체 페이지 영역 넘기기


지난번 마우스 휠로 input 넘버 값 up, down 작업을 했었다.

응용해서 작업 하나 더 했는데 올린다.


HTML

<div class="box1">박스1입니다.</div>
<div class="box2">박스2입니다.</div>
<div class="box3">박스3입니다.</div>
<div class="box4">박스4입니다.</div>
<div class="box5">박스5입니다.</div>
<div class="box6">박스6입니다.</div>
<div class="box7">박스7입니다.</div>

박스 7개 생성.

몇 개를 생성해도 상관없다.

하지만 구분을 위해 class로 css 추가했기 때문에 구분을 위한다면 똑같이 추가할 것. 


CSS

body,div{
  margin:0;
  padding:0;
}
div{
  display: flex;
  align-items: center;
  justify-content: center;
}
.box1{background-color:red;}
.box2{background-color:orange;}
.box3{background-color:yellow;}
.box4{background-color:green;}
.box5{background-color:blue;}
.box6{background-color:navy;}
.box7{background-color:purple;}


JS 수정 전

const _width = window.innerWidth;
const _height = window.innerHeight;
const boxArr = document.getElementsByTagName('div');

for(let i = 0; i < boxArr.length; i++){
  boxArr[i].style.width = _width + 'px';
  boxArr[i].style.height = _height + 'px';  
}

window.addEventListener('mousewheel', function(e){     
e.preventDefault();
   if(e.wheelDeltaY > 0){
     console.log('업');
     window.scrollTo(0,window.scrollY - _height);
   }else{
     console.log('다운');
     window.scrollTo(0,window.scrollY + _height);
   }
});
전체 페이지로 만들기 위해 window 크기 값을 가져와서 _width, _height 변수로 만들었다.   
반복문으로 각각에 _width, _height값을 주어 전체 페이지로 만들고

그 다음 마우스 휠 이벤트를 바인딩 해줬다.

마우스 휠 기본 이벤트를 막고 up, down 분기 코드로 현재 scrollTop위치에 박스 height 값을 더하거나 뺀 뒤 scrollTop 값이 되도록 했다.


+ mousewheel 이벤트는 예전에 브라우저 호환성 확인 안하고 작성한 스크립트를 가져다 썼기 때문에 호환이 안 될 수 있다. 


JS 수정내역!!

위의 js로 스크롤하게되면 스크롤하는 영역이 더해져서 (100px정도) 내가 원하는 페이지에 딱딱 안 멈추고 100px정도씩 어긋나는것이 확인된다.

따라서 window.scrollTo()에 들어가는 값에 스크롤 시 마다 내려가는 e.deltaY값을 빼줘야한다!

아래가 최종이다... 

근데 연속적으로 마우스 휠을하면 에러가 생기는데, jquery에서는 queue에 하나씩 들어가도록 stop()?메소드가 있는데, 아직 js는 모르겠다.

찾아서 다시 수정해야겠다..


JS 최종

const _width = window.innerWidth;
const _height = window.innerHeight;
const boxArr = document.getElementsByTagName('div');

for(let i = 0; i < boxArr.length; i++){
  boxArr[i].style.width = _width + 'px';
  boxArr[i].style.height = _height + 'px';  
}

window.addEventListener('mousewheel', function(e){     
e.preventDefault();
   if(e.wheelDeltaY > 0){
     console.log('업');
     window.scrollTo(0,window.scrollY - _height - e.deltaY);
   }else{
     console.log('다운');
     window.scrollTo(0,window.scrollY + _height - e.deltaY);
   }
});


[예제]

영역 안에서 마우스 휠을 업, 다운 해보도록!


See the Pen ePLmzp by leeyoonseo (@okayoon) on CodePen.




let, const 키워드

let 키워드, const 키워드를 알아보기 전에 var 키워드를 알아보자.

[var 키워드]

var 키워드는 변수를 선언할 때 사용하며 변수는 스코프(scope)로 구분한다.
크게 로컬 변수(Local variable), 글로벌 변수(Global variable)로 나뉜다.

로컬 변수(Local variable) - 함수, 오브젝트 
글로벌 변수(Global variable) - 프로그램 전체

ES5에서 vat 키워드를 사용하여 변수를 선언하도록 하기 위해 'use strict'를 도입했다.
'use strict'를 사용하면 var 없이 선언 시에 에러가 발생한다.

하지만 근본적으로 var의 문제를 해결하지 못한다.
그래서 var 키워드의 문제점을 해결하기 위해 나온 것이 let 키워드와 const 키워드이다.

[let 키워드]

1.함수 내에 작성하면 함수가 스코프다.
function () {
    let id = 'okayoon';
}

2.함수 내에 if문에 작성하면 if의 블록이 스코프다.
function (id) {
    if(id === 'okayoon'){
        let userId = id;
    }
}

3.블록 밖에 같은 이름의 변수가 있어도 스코프가 다르므로 각각 설정된 값이 유지된다.
let id = 'okayoon';

function (id) {
        let id = 'ok';
        console.log(id);
        // id의 값은 ok    
}
console.log(id);
// id의 값은 okayoon

4.블록 안에 블록을 계층적으로 작성하면 각각의 블록이 스코프다.
function (id) {
        let id = 'ok';

        function (){
            let id = 'okayoon';
            console.log(id);
            // id의 값은 okayoon
        }    

        console.log(id);
        // id의 값은 ok
}

5.같은 스코프에서 같은 이름으로 let 변수를 선언할 수 없다.
function (){
    let id = 'okayoon';
    ............
    ............
    let id = 'ok';
}    

6.호이스팅(Hoisting)

호이스팅(Hoisting)이란?
자바스크립트는 소스 코드 위에서 아래로 순차적으로 실행한다.
따라서 호출될 함수를 작성한 후 아래에서 함수를 호출해야 함수 호출이 정상적으로 된다.
하지만 함수 선언문은 호출하는 코드를 위에서 작성 후 호출 함수를 아래에서 작성해도 호출이 된다.
이를 호이스팅(Hoisting)이라고 한다.

let과 const 키워드는 호이스팅(Hoisting)되지 않는다고 알려져 있지만 실제로는 그렇지 않다고 한다.

예제의 경우 호이스팅(Hoisting)문제가 아니라 TDZ(Temporal Dead Zone)에 의해 ReferenceError를 발생한다.
let id = 'okayoon';

// 익명즉시실행함수
(function () {
    console.log(id);
    // undefined가 아니라 throws a ReferenceError 라고 한다.
}());
var 키워드 일 경우 function 함수가 먼저 선언된 것으로 인식되므로 console.log의 값은 undefined가 된다.
하지만 let과 const의 키워드는 호이스팅은 되나 TDZ에 의해 ReferenceError이 발생한다.

이해하려고 검색해서 찾아보았으나 정확히 모르겠다.
간단히 말해서 내부 로직 실행은 되는데, 그 안에서 문제가 생겨 바인딩 되지 못한다?
그래서 실행은 되니 호이스팅은 되는 것이고 과정에서 실패하여 언뜻 보았을때 호이스팅 자체가 안되는 것으로 보인다... 로 대충 이해하는 정도ㅠㅠ
자세한 것은 잘 정리해두신 블로거 글이 있어서 참고링크 로 걸어둔다.

7.this
var id = 'okayoon';
console.log(this.id);
// okayoon
var 키워드는 this로 글로벌 오브젝트의 id값을 출력한다.

let id = 'okayoon';
console.log(this.id);
// undefined
 let은 글로벌 오브젝트(window)에 설정되지 않는다.

[const 키워드]

1.변수에 할당된 값을 변경할 수 없다.
(할당된 값은 상수가 된다.)
const id = 'okayoon';

try{
    id = 'ok';
} catch(e){
    console.log('const 재할당 불가');
}
// 재할당 에러가 발생하고 try catch문에 의해 console.log의 문구가 실행된다.

2.값을 변경할 수 없다는 점을 제외하면 let 키워드와 기능 및 스코프가 같다.


+ Recent posts