簡體   English   中英

如何檢查屬性是否是Javascript中的函數

[英]How to check whether an attribute is a function in Javascript

在Javascript中,我想檢查一個attribut(或對象)是否是一個函數。

我現在的代碼:

if (this.execute != null)
{
    this.execute();
}

錯誤:對象不支持此屬性或方法。

我想做點什么

if (this.execute != null and isExecutableFunction(this.execute)== true )
{
    this.execute();
}

無論如何在Javascript中檢查屬性(或對象)是否是函數
任何幫助將不勝感激。
謝謝。

嘗試這個:

if(typeof this.execute == 'function') { 
this.execute(); 
}

你可以使用typeof

var func = function(){};
alert(typeof func)

如果你把它放在你的firebug控制台並運行它,你就會得到function作為返回。

所以你只需要檢查它。

嘗試這個。 在jsfiddle工作正常。 因為我沒有在函數內部工作,所以我將其更改為t。 嘗試使用第2行標記和未標記。

var t= new Object;

//t.execute = function() { alert('executing'); };

if(t.execute)  
   t.execute();
else
    //code here when execute fails
  alert('Function could not execute');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM