Search code examples
javascriptjqueryobjectthisprototype-programming

Refering to Javascript "Class" method from jQuery function


How to I refer to a parent "class" method in Javascript from a jQuery function? Example:

$Object.prototype.TestFunction = function(arg){
  alert(arg);
}

$Object.prototype.foo = function(){
    $(something).click(function(){
        this.TestFunction("Hello"); //Obviously doesn't work.
    });
}

I have predictable sets of data that need to be manipulated for multiple sets and results viewed on the page, which is why I built an object to handle it. However, when I use anything "jQuery" and try to refer to an object property or method from within, it obviously doesn't work.

Is this possible?

Thank you very much for your time and effort, in advance.


Solution

  • My preferred method is with using $.proxy:

    $Object.prototype.foo = function(){
        $(something).click($.proxy(this.TestFunction,this);
    };
    

    It's cleaner and also passes through any arguments (like the event) to the handler function.