Search code examples
javascriptmethodsoverridingparent

Overriding a Javascript method only if it does not exist


My goal here is to override a method if it isn't found, otherwise use the original method (for backwards compatibility of a library I can't alter).

This is what I have so far, but am still struggling with:

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

I want to have getDatasource() check if it exists, if not, call getStore(). If it does exist, just use the original getDatasource(). I know this breaks because I haven't figured out how to reference the parent 'this' scope. When I work around that issue I get into a recursive loop as it keeps trying to override itself. If you have a better way of doing this please let me know!


Solution

  • i think this should do what you want.

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

    this statement will try to find something that evaluates truish from left to right. when it finds that thing, it will use it as the value for the assignment. in this case if getDataSource is undefined it'll evaluate as false, and getStore will be checked. getStore exists so it'll evaluate to (roughly) true, and so the function reference will be assigned to this.grid.getDataSource.getDataSource;