code

eval ()과 new Function ()은 같은 것입니까?

codestyles 2020. 9. 22. 08:13
반응형

eval ()과 new Function ()은 같은 것입니까?


이 두 기능이이면에서 동일한 작업을 수행합니까? (단일 명령문 함수에서)

var evaluate = function(string) {
    return eval('(' + string + ')');
}

var func = function(string) {
    return (new Function( 'return (' + string + ')' )());
}

console.log(evaluate('2 + 1'));
console.log(func('2 + 1'));

아니요, 동일 하지 않습니다 .

  • eval() 현재 실행 범위 내에서 문자열을 JavaScript 표현식으로 평가하고 로컬 변수에 액세스 할 수 있습니다.
  • new Function()문자열에 저장된 JavaScript 코드를 함수 객체로 구문 분석 한 다음 호출 할 수 있습니다. 코드가 별도의 범위에서 실행되기 때문에 지역 변수에 액세스 할 수 없습니다.

이 코드를 고려하십시오.

function test1() {
    var a = 11;
    eval('(a = 22)');
    alert(a);            // alerts 22
}

사용 된 경우 new Function('return (a = 22);')()지역 변수 a는 해당 값을 유지합니다. 그럼에도 불구하고 Douglas Crockford와 같은 일부 JavaScript 프로그래머 절대적으로 필요한 경우가 아니면 둘 다 사용해서는 안된다고 생각하며 Function신뢰할 수없는 데이터 에서 생성자를 평가 / 사용하는 것은 안전하지 않으며 현명하지 않습니다.


아니.

업데이트 에서 동일한 결과를 호출 evaluate하고 func생성합니다. 그러나 그들은 "뒤에서 똑같은 일을하는 것"이 ​​가장 확실합니다. func함수는 새 함수를 생성하지만 즉시 실행하는 반면, evaluate함수는 그 자리에서 코드를 실행합니다.

원래 질문에서 :

var evaluate = function(string) {
    return eval(string);
}
var func = function(string) {
    return (new Function( 'return (' + string + ')' )());
}

이는 매우 다른 결과를 제공합니다.

evaluate('0) + (4');
func('0) + (4');

new Function재사용 할 수있는 함수를 만듭니다. eval주어진 문자열을 실행하고 마지막 문의 결과를 반환합니다. 평가를 에뮬레이트하기 위해 Function을 사용하는 래퍼 함수를 ​​만들려고 시도했을 때 질문이 잘못되었습니다.

그들이 커튼 뒤에서 몇 가지 코드를 공유한다는 것이 사실입니까? 예, 가능성이 높습니다. 정확히 같은 코드? 아뇨.

For fun, here's my own imperfect implementation using eval to create a function. Hope it sheds some light into the difference!

function makeFunction() {
  var params = [];
  for (var i = 0; i < arguments.length -  1; i++) {
    params.push(arguments[i]);
  }
  var code = arguments[arguments.length -  1];


 // Creates the anonymous function to be returned
 // The following line doesn't work in IE
 // return eval('(function (' + params.join(',')+ '){' + code + '})');
 // This does though
 return eval('[function (' + params.join(',')+ '){' + code + '}][0]');
}

The biggest difference between this and new Function is that Function is not lexically scoped. So it wouldn't have access to closure variables and mine would.


If you mean, will it yield the same results, then yes... but just to eval (aka, "evaluate this string of JavaScript") would be much simpler.

EDIT Below:

It's like saying... are these two math problems the same:

1 + 1

1 + 1 + 1 - 1 + 1 - 1 * 1 / 1


In that example, the results are the same, yes. Both execute the expression you pass. This is what makes them so dangerous.

But they do different things behind the scense. The one involving new Function(), behind-the-scenes, creates an anonymous function from the code you supply, which is executed when the function is invoked.

The JavaScript you pass to it is technically not executed until you invoke the anonymous function. This is in contrast to eval() which executes the code right away, and doesn't generate a function based on it.


Just want to point out some syntax used in the examples here and what it means:

 var func = function(string) {
     return (new Function( 'return (' + string + ')' )());
 }

notice that the Function(...)() has the "()" at the end. This syntax will cause func to execute the new function and return the string not a function that returns string, but if you use the following:

 var func = function(string) {
     return (new Function( 'return (' + string + ')' ));
 }

Now func will return a function that returns a string.

참고URL : https://stackoverflow.com/questions/4599857/are-eval-and-new-function-the-same-thing

반응형