[Small-Tip] JavaScript eval()이란, 그리고 이를 대체할 new Function()

Mubby·2022년 4월 15일
3

소소팁(9xx)

목록 보기
4/5
post-thumbnail

The eval() Function


MDN에서 eval()은 문자로 표현 된 JavaScript 코드를 실행하는 함수라고 정의되어있습니다.
즉, 문자열(String)을 코드로 인식해 실행할 수 있게 해주는 함수라고 보시면 됩니다.

eval()을 사용하면 아래와 같은 코드를 사용할 수 있습니다.

let a = 3;
let b = 5;
eval('a += ' + b + ' + 2');
console.log(a); // 10

예시를 잘 못들겠지만 이런식으로 코드를 작성할 수 있게 된다면 은근히 사용할 일이 많습니다;;;

하지만 eval()에는 보안 이슈가 존재합니다.

eval()은 인자로 받은 코드를 caller의 권한으로 수행하는 함수로, 악영향을 줄 수 있는 문자열을 eval() 로 실행하면 악의적인 코드를 수행하는 결과를 초래할 수 있습니다.

또한 제 3자가 eval()이 호출된 위치의 스코프를 볼 수 있으며, Function으로 실행할 수 없는 공격이 가능하다고 합니다. (더 자세한 사항은 여기를 참고하세요.)

다행히 eval()은 new Function()으로 대체할 수 있습니다.


new Function()


new Function()는 문자열을 코드로 인식해 실행한다는 점에서 eval 함수와 유사합니다.

하지만 new Function()은 별도의 함수 영역으로 분리되어 함수 내부 Scope에만 접근과 수정이 가능하며, 내부에서 선언된 변수 등은 해당 Function 안에서만 유효하기 때문에 eval과 같은 보안 이슈가 없습니다.

  • new Function() 의 기본 문법
let func = new Function ([arg1, arg2, ...argN], functionBody);

  • eval()과 new Function()의 Scope 비교
function Myfunc1() {
  let a = 123;
  eval('console.log(a); a = 456;');
  console.debug(a);
}
Myfunc1(); // 123, 456

function Myfunc2() {
  let b = 123;
  new Function('console.log(b);')(); // ReferenceError: b is not defined
}
Myfunc2();


참고사이트 :
MDN
모던 JavaScript 튜토리얼

profile
코딩으로 평생 먹고 살자!

2개의 댓글

comment-user-thumbnail
2023년 8월 28일

I'm a computer science student and started learning Java Script just a year ago. I have got some basic understanding of code allowing me to read it, while I hear about the Eval function for the first time. I should have spent more hours learning code, instead of visiting https://assignmentcore.com/javascript-homework/ for getting help with JavaScript homework every time I was unfamiliar with anything in JS code. Their online experts were quiet effective and supposedly used Eval in their code, however it's way more practical for a developer to read an explanation with examples rather than relying on someone else.

답글 달기
comment-user-thumbnail
2023년 9월 29일

The level in the game geometry dash bloodbath is a mega-collaboration and is classed as an Extreme Demon, the degree of difficulty with the highest score. Riot, a player, was responsible for creating, hosting, validating, and publishing it.

답글 달기