Javascript 如何检查对象是否具有函数?(道场)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14961891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an object has a function? (DoJo)
提问by antonpug
var testObj = this.getView();
How can I check with DoJo (or just native JS) if testObj has callableFunctionbefore I actually try to call callableFunction()and fail if it isn't there? I would prefer a native-DoJo solution as I need this to work on all browsers.
如果 testObjcallableFunction在我实际尝试调用callableFunction()并失败之前,我如何使用 DoJo(或仅使用原生 JS)检查它是否存在?我更喜欢原生 DoJo 解决方案,因为我需要它在所有浏览器上工作。
回答by dfsq
You can call it like this:
你可以这样称呼它:
testObj.callableFunction && testObj.callableFunction();
or in details:
或详细说明:
if (typeof testObj.callableFunction == 'function') {
testObj.callableFunction();
}
回答by Craig Swing
dojo has a function that you can use to perform the test.
dojo 有一个可以用来执行测试的函数。
require(["dojo/_base/lang"], function(lang){
var testObj = this.getView();
if(lang.isFunction(testObj.callableFunction)){
testObj.callableFunction();
}
});
回答by jbabey
You should test that the property exists and is a function:
您应该测试该属性是否存在并且是一个函数:
var returnFromCallable = typeof testObj.callableFunction === 'function' &&
testObj.callableFunction();

