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"
謝謝!
正如下面的reko_t回答,你有'instanceof'。正如你發現的那樣,'typeof'只會產生與JavaScript中的內建類型相對應的值。 – Peter 2011-06-14 15:04:16
@Peter,+1,很棒的評論! – Cybrix 2011-06-14 15:06:08