简体   繁体   中英

Is there a way to variably name a function

I would like to variably assign a name to a new function, is this possible?

function returnFunctionWithName(str){
  return function(){
    return srt
  }
}

var x = returnFunctionWithName("hello")

console.log(x) // => [Function]

What I want is something like this: (this doesn't work)

function returnFunctionWithName(str){
  return function [str](){
    return srt
  }
}

var x = returnFunctionWithName("hello")

console.log(x) // => [Function: hello]

Just tried this too with no effect:

function returnFunctionWithName(str){
  var x = function(){
    return str
  }
  x.name = str
  return x
}

var x = returnFunctionWithName("hello")

console.log(x) // => [Function: hello]

You can technically set a function's name property as follows:

Object.defineProperty(theFunction, 'name', {
    get: function() { 
        return 'NewFunctionName'; 
    }
});

However, I don't know if this solves your problem, as in my quick tests this didn't actually render the expected name when console.log 'ing the function.

The reason that x.name = str doesn't work is that Function#name isn't writable . It is , however, "Configurable", which means you can mess with it via Object.defineProperty() .

The only cross-browser way I have found to do what you are asking is actually very unsafe in many circumstances... So, with care, the answer is below.

 function makeNewFunction(name) {
    return eval('(function(){ return function ' + name + '() {' +
        ' // code as a string' +
        + '}; }) ();');
 }

I had to use something like this awhile ago using a technique I call evilclassing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM