아티클 목록

eval(), new Function()의 차이

eval(), new Function()?

웹 앱에 eval()가 포함돼 있으면 취약점 검사 시 JS Code Injection이 가능해서 문제가 된다. 때문에 문자열로 된 JS Code를 실행시키기 위해선 eval()보다 Function()를 쓰는게 권장된다. (new 키워드는 생략 가능)

// eval
var a = eval("alert('hi')");
 
// Function constructor
var b = Function("alert('hi')")();

차이점은?

가장 큰 차이점은 scope, eval()은 호출 시점 scope를 가진 채 코드가 실행돼 지역 변수에 접근 가능하지만, Function()은 전역(window) scope를 갖는다. 만약 현재 스코프나 지역변수가 필요하다면 인자로 전달해서 사용해야 한다.

function funcA() {
    var a = "hi";
 
    eval("console.log(a)");
}
 
funcA(); // 'hi', eval 스코프에 a를 사용
 
function funcB() {
    var b = "there";
 
    Function("console.log(b)")();
}
 
funcB(); // undefined,window에 b가 없으므로
 
function funcC() {
    var c = "young";
 
    Function("console.log(arguments[0])")(c); // 인자로 전달
}
 
funcC(); // 'young'

참고

댓글