2011-06-14 50 views
0

我在玩JS.Class v.3.0 http://jsclass.jcoglan.com/,我想找到一種方法來檢測對象的實例。如何檢查返回值是否爲JS.Hash?

  var Car = new JS.Class({ 
       hColors : new JS.Hash([]), 

       initialize : function() { 
        this.hColors.store("1", "red "), 
        this.hColors.store("2", "green "), 
        this.hColors.store("3", "blue ") 
       }, 

       getColors : function(colorId, returnHash) { 
        if (this.hColors.get(colorId)) 
        { 
         var currentObjects = this.hColors.get(colorId); 

         if (returnHash) 
         { 
          return new JS.Hash([ 
           colorId, currentObjects 
          ]); 
         } 

         return currentObjects; 
        } 

        return this.hColors; 
       } 
      }); 

      var F150 = new Car(); 

      var F150Colors = F150.getColors(); //Hash:{1=>red ,2=>green ,3=>blue } 
      //var F150Colors = F150.getColors("2", false); //String:green 
      //var F150Colors = F150.getColors("2", true); //Hash:{2=>green } 

      //How do I test if F1250 is an instance of JS.Hash? 

正如可以看到的,getColors方法可以接受兩個參數,這將要麼返回整個哈希,含有1個值或簡單地選擇的值的選擇的哈希。

現在的問題是:我如何檢查F150Colors是否是JS.Hash的實例?

解決方案:typeof F150Colors == "string"是不夠的,因爲最終,我的hColors將包含對象({})。而且一切都將是一個typeof F150Colors == "object"

謝謝!

+1

正如下面的reko_t回答,你有'instanceof'。正如你發現的那樣,'typeof'只會產生與JavaScript中的內建類型相對應的值。 – Peter 2011-06-14 15:04:16

+0

@Peter,+1,很棒的評論! – Cybrix 2011-06-14 15:06:08

回答

4
if (F150Colors instanceof JS.Hash) 
+0

哦...傻了。謝謝! – Cybrix 2011-06-14 15:02:45

相關問題