当像变量一样访问函数时,添加字符串的返回类型 [英] Add a return type of string when a function is accessed like a variable

查看:58
本文介绍了当像变量一样访问函数时,添加字符串的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这是否可行(事实上,我正在努力寻找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
}

这篇关于当像变量一样访问函数时,添加字符串的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆