kgneng2 / blokg

blog
MIT License
0 stars 0 forks source link

new Function 문법 #4

Open kgneng2 opened 4 years ago

kgneng2 commented 4 years ago

'new Function' 문법

let sayHi = function() {
  alert( "Hello" );
};

function sayHi() {
  alert( "Hello" );
}

문법

let func = new Function ([arg1, arg2, ...argN], functionBody);

새로 만들어지는 함수는 인수 arg1...argN과 함수 본문 functionBody로 구성됩니다.

example

let sum = new Function('a', 'b', 'return a + b');

alert( sum(1, 2) ); // 3

클로저

example

let value ="hello";
function getFunc() {

  let func = new Function( 'alert(value)' );

  return func;
}
getFunc() //'hello' alert
function getFunc() {
  let value = "test";

  let func = new Function('alert(value)');

  return func;
}

getFunc(); // ReferenceError: value is not defined

minify

function getFunc() {
  let value = "test";

  let func = new Function('alert(value)');

  return func;
}
getFunc();
// minify 
function getFunc(){let b='test';let a=new Function('alert(value)');return a;}

번외 eval