admin管理员组文章数量:1302270
I know how to check to see if a property of the global context exists. Any variation of
if (typeof myFunction != 'undefined'){...}
but what if I don't know the name of the function? I think globally I could do this
if (typeof this['myFunction'] != 'undefined'){...}
but I don't know how to do that in a function like this
function load(functionName){
if (typeof GLOBALCONTEX[functionName] != 'undefined'){
GLOBALCONTEX[functionName](arg1 , arg2 , ...);
}
}
And I don't want to use try/catch as I have heard it is slow.
I know how to check to see if a property of the global context exists. Any variation of
if (typeof myFunction != 'undefined'){...}
but what if I don't know the name of the function? I think globally I could do this
if (typeof this['myFunction'] != 'undefined'){...}
but I don't know how to do that in a function like this
function load(functionName){
if (typeof GLOBALCONTEX[functionName] != 'undefined'){
GLOBALCONTEX[functionName](arg1 , arg2 , ...);
}
}
And I don't want to use try/catch as I have heard it is slow.
Share asked Jul 12, 2011 at 20:34 pukpuk 16.8k31 gold badges124 silver badges205 bronze badges3 Answers
Reset to default 9If working with a browser, substitute GLOBALCONTEX
with window
. Example:
function load(functionName){
if (typeof window[functionName] != 'undefined'){
window[functionName](arg1 , arg2 , ...);
}
}
The Globalcontext is window. All objects are attached to it.
function load(functionName){
if (typeof window[functionName] != 'undefined'){
window[functionName](arg1 , arg2 , ...);
}
}
In the browser, the global object is window
[docs]. If you use another JavaScript execution environment (like Node.js), have a look at its documentation to find out the name/reference to the global object.
Of course such a test only works for functions which are defined in global scope, not in any higher scope. So it might be that such a function is available (and accessible) but it is not in the global scope.
本文标签: Javascript Finding if FunctionClass exists before calling itStack Overflow
版权声明:本文标题:Javascript Finding if FunctionClass exists before calling it - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741666857a2391361.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论