Javascript 如何在TypeScript中将函数作为变量调用
示例:Javascript 如何在TypeScript中将函数作为变量调用,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,示例: if (this.isElementLoaded) { //output true } 创建函数 const isElementLoaded = () => { //Logic return true; } 使用this.isElementLoaded调用函数: if (this.isElementLoaded) { //output true } 如果不想使用(),则需
if (this.isElementLoaded)
{
//output true
}
创建函数
const isElementLoaded = () => {
//Logic
return true;
}
使用this.isElementLoaded调用函数:
if (this.isElementLoaded)
{
//output true
}
如果不想使用
()
,则需要将其设置为访问器属性。(在没有()
的情况下调用它的唯一其他方法是将其用作标记模板文本上的标记函数,这似乎与您正在执行的操作无关。:-)
在类中,您可以这样做:
class Example {
get isElementLoaded() {
return /*...appropriate value...*/;
}
}
在对象文字中,它基本上是相同的:
const obj = {
get isElementLoaded() {
return /*...appropriate value...*/;
}
};
在任何一种情况下,TypeScript都应该能够从return
语句中推断返回类型,但如有必要,可以添加注释,例如:
class Example {
get isElementLoaded(): boolean {
return /*...appropriate value...*/;
}
}
如果要在对象创建后向其添加访问者,请使用defineProperty
:
Object.defineProperty(obj, "isElementLoaded", {
get() {
return /*...appropriate value...*/;
},
// flags here if appropriate; they default to `false` if omitted
});
您需要确保对象的类型信息包括访问器(可能作为可选属性)。或者使用函数,然后需要使用()
调用函数(这是TypeScript/JavaScript语法):
或者,您可以将类上的属性与getter一起使用:
get isElementLoaded() {
//Logic
return true;
}
// in a function
if (this.isElementLoaded) {
//output true
}
tl;dr:使用这个
实际上,您并没有调用在那里创建的函数。如果使用箭头符号来创建函数,则可以对
function isElementLoaded(...){...}
这会更清楚地表明,也许你必须打电话给它来实际做一些事情。只需调用函数名,就可以引用函数体,但这并没有任何进展。
下面是一个快速试用示例:
点击“run”,您会看到输出中的差异。this.isElementLoaded()
?(顺便说一句,与typescript或javascript中的任何函数一样)我不想使用圆括号。您可以使用getter,它就像属性一样使用get isElementLoaded():boolean{return true;}
为什么不使用括号?@evolutionxbox可能是他的(,)键损坏/不起作用?谢谢,我得到了答案!!!