tags:

views:

88

answers:

4

I'm trying to make some existing JS backwards compatible. I need to override a method if it does not exist, otherwise just return the existing method.

Here is the code I have so far:

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

However it keeps returning an error on the "if" line:

getDataSource is undefined

What is the best way of going about this?

+5  A: 

This should work without throwing an error.

if (typeof getDataSource != "function")
Pekka
I'd prefer testing `(typeof getDataSource == "function")`, as testing for it not being `undefined` (cf. the else clause) doesn't reveal it actually *represents* a function; the variable might as well refer to a string or other primitive.
Marcel Korpel
@Marcel of course, you're right. Removing the second variation.
Pekka
Ah, I just saw you [always get capitalization wrong](http://area51.stackexchange.com/proposals/14873/english-german-translation). ;)
Marcel Korpel
This does it, thanks a lot!
Fook
A: 

you might need to wrap it in a typeof() function

this.grid.getDataSource = function(){
if (typeof getDataSource == undefined)
    return getStore();
    else return getDataSource();
}
davidsleeps
FYI, *typeof* is not a function - it's an operator. You don't need the parens (see [Pekka's answer](http://stackoverflow.com/questions/3552383/testing-the-existence-of-a-method/3552392#3552392)). I learned that the hard way here on SO :-)
Andy E
this is why I love SO, you learn stuff!
davidsleeps
@davidsleeps: yeah, I've learned a lot since joining this site :-)
Andy E
it may be an operator, but I use parenthesis a lot of the time just to make it more readable, especially if you are doing "typeof(asd.getName)" or something
jdc0589
A: 

this.grid.getDataSource = getDataSource || getStore;

jdc0589
This will still throw an error if *getDataSource* hasn't been declared.
Andy E
A: 

Here is a nice resourse, which should answer to your question. It's a pretty simple function.

http://phpjs.org/functions/method_exists:471

Jevgeni Bogatyrjov
OMG, what's this? Using a custom function for *one* simple comparison isn't very efficient...
Marcel Korpel