0

I'm trying to setup a speed test for functions. It works when I pass in a function directly, but I'd like to offer co-workers a form to cut and paste their own.

    function sendTest() {
        //fName, fContent
        var fName = document.getElementById("fName").value;
        var fContent = document.getElementById("fContent").value;
        var f = new Function(fName, fContent);
        f.name = fName;
        testTime(f);
    }

testTime() is the function to evaluate performance, and evaluating time of execution is working correctly from sendTest(), but I can't access the function name from testTime() to display the function name with the results. f.name and f.fName both come up as undefined.

A function is an object, right? So I should be able to apply a name propery to it?

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 1
    A function's name property is a special one that is read-only, see here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name – axelduch Jun 15 '14 at 03:24
  • And `Function` is defined as: `new Function ([arg1[, arg2[, ...argN]],] functionBody)` – elclanrs Jun 15 '14 at 03:24
  • `eval` is the only way: `var foo = eval( '(function ' + name + '(){})' );` –  Jun 15 '14 at 03:26
  • Thank you! Think there's another way to pass the function so it still executes, but I can attach a name (as an object instead of a function maybe?) – user2925994 Jun 15 '14 at 03:26
  • 1
    I reopened the question (unmarked it as a duplicate) because the OP's specific question is solved is not as generic as needing to assign THE specific name property which is what the duplicate tries to address. There's a much simpler method of addressing the OP's specific problem in my answer. – jfriend00 Jun 15 '14 at 03:36
  • @jfriend00: OK, I though OP was asking specifically about "***naming** a dynamically generated function*", which [the possible duplicate](https://stackoverflow.com/questions/9479046/is-there-any-non-eval-way-to-create-a-function-with-a-runtime-determined-name) would have explained. I thought that using a different property than `name` was too obvious, given also the link in aduch's comment… – Bergi Jun 15 '14 at 04:17

1 Answers1

1

This seems like a much simpler answer for your specific problem than the what someone else marked your question a duplicate of.

In ES6, there is a built-in .name property of a Function which is NOT writable so that's why you can't assign to it (link to specific section of draft ES6 spec). You should be able to use a different property name if you want to assign a name the way you are doing so.

Working demo using a different property name: http://jsfiddle.net/jfriend00/6PVMq/

f = new Function("log('Hello')");
f.myName = "sayHi";

function testFunc(func) {
    log("function name is: " + func.myName);
    func();
}

testFunc(f);
jfriend00
  • 683,504
  • 96
  • 985
  • 979