Fook
Fook

Reputation: 5550

Testing the existence of a method

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?

Upvotes: 2

Views: 228

Answers (4)

Pekka
Pekka

Reputation: 449415

This should work without throwing an error.

if (typeof getDataSource != "function")

Upvotes: 6

jdc0589
jdc0589

Reputation: 7018

this.grid.getDataSource = getDataSource || getStore;

Upvotes: 1

bogatyrjov
bogatyrjov

Reputation: 5378

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

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

Upvotes: 0

davidsleeps
davidsleeps

Reputation: 9503

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

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

Upvotes: 1

Related Questions