[英]How to check if function is exist or not in javascript
我想檢查該類是否在javascript中具有方法。 假設要檢查正常功能,我可以使用-
使用jQuery:
function foo(){}
if($.isFunction(foo)) alert('exists');
或從普通的javascript:
function foo(){}
if(typeof foo != 'undefined') alert('exists');
但是我想檢查一個成員函數,例如我是否有一個類和方法,例如-
function ClassName(){
//Some code
}
ClassName.prototype.foo = function(){};
我有一個存儲在變量中的方法名稱,我正在使用此變量調用該方法,例如-
var call_it = 'foo';
new ClassName()[call_it]();
但是對於處理運行時錯誤,我想在調用之前檢查該方法是否存在。 我怎樣才能做到這一點?
if (ClassName.prototype[call_it]) {
new ClassName()[call_it]();
}
var call_it = 'foo';
if (typeof ClassName.prototype[call_it] === "function"){
new ClassName()[call_it]();
}
要么
var call_it = 'foo';
var instance = new ClassName();
if (typeof instance[call_it] === "function"){
instance[call_it]();
}
您應該使用typeof來確保該屬性存在並且是一個函數
if ( typeof yourClass.foo == 'function' ) {
yourClass.foo();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.