如何验证JavaScript中是否定义了函数?

时间:2022-03-29 07:06:30

How can I verify if a function was defined already?

如何验证函数是否已定义?

Will this work?

这会有用吗?

if(window.opener.MyFunctionBlah) {  ...  }

2 个解决方案

#1


if (typeof yourFunctionName === 'function') {
    yourFunctionName();
}

#2


Yes. Functions are just properties of objects like any other, so you can treat them as such. The conditional you posted above will return true if that function (or any member of window.opener called MyFunctionBlah) is defined and non-null.

是。函数只是对象的属性,因此您可以将它们视为对象。如果定义了该函数(或window.opener的任何成员名为MyFunctionBlah)并且为非null,则上面发布的条件将返回true。

#1


if (typeof yourFunctionName === 'function') {
    yourFunctionName();
}

#2


Yes. Functions are just properties of objects like any other, so you can treat them as such. The conditional you posted above will return true if that function (or any member of window.opener called MyFunctionBlah) is defined and non-null.

是。函数只是对象的属性,因此您可以将它们视为对象。如果定义了该函数(或window.opener的任何成员名为MyFunctionBlah)并且为非null,则上面发布的条件将返回true。