Add a return type of string when a function is accessed like a variable

荒凉一梦 提交于 2019-12-31 05:19:35

问题


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

I have a function

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

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?


回答1:


Is it possible to achieve this via Object proxies somehow?

No, this is not possible. You cannot make a callable proxy as a primitive string. If you want your test (function) object to show a custom string when stringified (like when concatenated to an other string), just give it a custom .toString() method:

const test = Object.assign(() => "Hello World", {
  toString() {
    return "123";
  }
});
console.log("Example call " + test());
console.log("Example stringification " + test);
console.log("Function object", test);
console.log("as a string", String(test));



回答2:


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
}


来源:https://stackoverflow.com/questions/53328945/add-a-return-type-of-string-when-a-function-is-accessed-like-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!