본문 바로가기
JavaScript

[JS] 자바스크립트에서 변수 안에 함수 넣기 / eventListener

by Meaning_ 2022. 7. 7.
728x90
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const colors = ["#1abc9c""#3498db""#9b59b6""#f39c12""#e74c3c"];
// <⚠️ /DONT DELETE THIS ⚠️>
const hello = document.querySelector("h2");
const superEventHandler = {
  mouseEnter: function () {
    hello.innerText = "The mouse is here!";
    hello.style.color = colors[0];
  },
  mouseLeave: function () {
    hello.innerText = "The mouse is gone";
    hello.style.color = colors[1];
  },
  contextMenu: function () {
    hello.innerText = "That was a right click!";
    hello.style.color = colors[2];
  },
  resize: function () {
    hello.innerText = "You just resized!";
    hello.style.color = colors[3];
  }
};
hello.addEventListener("mouseenter", superEventHandler.mouseEnter);
hello.addEventListener("mouseleave", superEventHandler.mouseLeave);
hello.addEventListener("contextmenu", superEventHandler.contextMenu);
window.addEventListener("resize", superEventHandler.resize);
 
cs

변수 안에 함수 넣기

자바스크립트에서 변수 안에 함수들을 넣는 방법을 알아볼 수 있었다.

 

const 변수명={

  함수명:function(){

 

   },

  함수명:function(){

 

   }

}

 

이런형식으로 변수 안에 함수를 넣어준다.

 

 

이렇게 쓰는 이유가 뭘까?

https://jsdev.kr/t/function/4549/3

 

자바스크립트는 왜 변수에 function을 넣는 경우가 많나요?

자바스크립트의 함수는 1급객체로 1급객체라 함은 변수에 넣을 수도 있고 함수의 인자로도 넘길 수 있고 함수의 리턴값으로도 넘길 수 있다는 것을 의미합니다. 이러한 특성 덕분에 @bugtype 님께

jsdev.kr

const 변수에 넣어서 함수가 바뀌지 않도록 하는 것이다. 자바스크립트에서 함수는 1급 객체인데, 이는 변수에 넣을 수도 있고, 함수의 파라미터로도 넘길수 있고, 함수의 리턴값으로도 넘길 수 있다.

https://velog.io/@reveloper-1311/%EC%9D%BC%EA%B8%89-%EA%B0%9D%EC%B2%B4First-Class-Object%EB%9E%80

 

일급 객체(First Class Object)란?

자바스크립트를 공부하다보면 라는 말을 한 번쯤은 들어보았을 것이다. 이번에는 그 가 무엇인지에 대해서 정리해보고자 한다. 일급 객체(1급객체, First Class Object) 일급객체에 대한 정의이다. >

velog.io

이벤트 리스너 달아주기

 

만약 마우스가 hello 텍스트 밖으로 갔을 때 "mouseleave" 이벤트가 실행되면서 superEventHandler.mouseLeave라는 함수가 실행된다. 그럴려면 자바스크립트의 이벤트 함수인 mouseleave를 호출해줘야한다.

hello.addEventListener("mouseleave",superEventHandler.mouseLeave) 

728x90
반응형

댓글