当像变量一样访问函数时,添加字符串的返回类型

问题描述:

我不确定这是否可行(事实上,我正在努力寻找Google的用途),但是事情就这样了:

I am not sure if this is possible (in fact I'm struggling to work out what to google for) but here it goes:

我有一个功能

const test = () => {
  some logic..
  return bla
}

现在当我使用'test()'时,我希望函数执行.但是,当我使用测试"时,我希望返回一个自定义字符串.是否可以通过Object代理以某种方式实现这一目标?

now when I use 'test()' I want the function executed. But when I use 'test' I want a custom string to be returned. Is it possible to achieve this via Object proxies somehow?

如果首先检查变量的类型,则可以执行此操作,尤其是要检查其 Function :

You can do this if you first check the type of the variable, in particular you will check if its a Function:

function isFunc(functionToCheck) {
 return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
};

因此,如果为真,则您的变量实际上是一个函数,您可以从中返回所需的内容:

So if this is true, then your variable is infact a function and you can return the stuff you need from it:

const isItAFunction = somevariable;

if(isFunc(isItAFunction)) {
   // return your string
} else {
  // do something else
}