2010-08-23 56 views
2

我試圖讓一些現有的JS向後兼容。我需要重寫一個方法,如果它不存在,否則只是返回現有的方法。測試方法的存在

這裏是我的代碼至今:

this.grid.getDataSource = function(){ 
    if (getDataSource == undefined) 
     return getStore(); 
    else 
     return getDataSource(); 
} 

但是它保留了 「如果」 行返回一個錯誤:

了getDataSource是不確定的

是什麼這是怎麼回事?

回答

6

這應該沒有任何錯誤。

if (typeof getDataSource != "function") 
+0

我寧願測試'(typeof運算==了getDataSource 「功能」)',以測試它不是'undefined'(參見else子句)沒有透露它實際上*代表*功能;該變量也可能引用一個字符串或其他原語。 – 2010-08-23 23:35:56

+0

@Marcel當然,你是對的。刪除第二個變體。 – 2010-08-23 23:38:07

+0

啊,我剛剛看到你[總是弄錯大寫](http://area51.stackexchange.com/proposals/14873/english-german-translation)。 ;) – 2010-08-23 23:57:18

1

您可能需要將其包裝在一個typeof運算 ()函數

this.grid.getDataSource = function(){ 
if (typeof getDataSource == undefined) 
    return getStore(); 
    else return getDataSource(); 
} 
+1

僅供參考,* typeof *不是函數 - 它是一個運算符。你不需要parens(參見[Pekka的答案](http://stackoverflow.com/questions/3552383/testing-the-existence-of-a-method/3552392#3552392))。我瞭解到,在這裏的艱辛之路:-) – 2010-08-23 23:13:56

+1

這就是爲什麼我喜歡這樣,你學習的東西! – davidsleeps 2010-08-23 23:15:11

+0

是的,自從加入這個網站以來,我學到了很多東西:-) – 2010-08-23 23:16:07

1

this.grid.getDataSource = ||了getDataSource getStore;

+0

如果* getDataSource *沒有被聲明,這仍然會拋出一個錯誤。 – 2010-08-23 23:15:04