简体   繁体   English

有没有一种可变地命名功能的方法

[英]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: 您可以从技术上设置函数的name属性,如下所示:

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. 但是,我不知道这是否可以解决您的问题,因为在我的快速测试中,console.log函数使用该功能时,它实际上并未呈现预期的名称。

The reason that x.name = str doesn't work is that Function#name isn't writable . x.name = str不起作用的原因是Function#name 不可写 It is , however, "Configurable", which means you can mess with it via Object.defineProperty() . 但是,它 “可配置的”,这意味着您可以通过Object.defineProperty()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. 不久前,我不得不使用一种称为“邪恶分类”的技术来使用这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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