0

How does one go about dynamically creating a function in javascript, but have a variable be "dynamically hardcoded" (?). Preferably without using eval().

I thought this would be the cleanest way to pass async.parallel() a few parameters in nodejs without having to bind objects.

function makeFunction( param1){

  return function(){
      alert(param1); 
  }

}

Actual Output from console.log( makeFunction("Hello World") );

return function(){ alert(param1); }

Desired Output from console.log( makeFunction("Hello World") );

return function(){ alert("Hello World"); }

2
  • 2
    Why do you want to hard code it? It will anyways hold on to 'Hello World' because of clojure. If you call it again with "Bye World", it will still return as attached to param1, but param1 there, because of clojure, will have 'Bye World' Commented Feb 23, 2014 at 15:39
  • 1
    Only because you don't see the closure scope in the output, param1 === "Hello World". There is no need to create a function that contains the string literal in its source code, it even would be less performant than the closure. Commented Feb 23, 2014 at 15:41

2 Answers 2

1
function makeFunction(param1){
  return new Function('alert(\'' + param1 + '\');')
}

console.log(makeFunction('helloWorld').toString())

only like that. new Function is a little bit "evaly" but in fact it's much better (or less evil).

0

I don't feel it'd be better than using eval, but probably this would be what you want:

function makeFunction(param1) {
    var F=function () {
        alert(param1);
    };

    var text=['"', '"'].join(param1);
    text=String.prototype.replace.call(F, 'param1', text);
    text=['return ', ';'].join(text);
    return (new Function(text))();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.