1

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.

2 Answers 2

4

Simply assign this to a variable and in your closure reference the variable.

$Object.prototype.foo = function(){
    var that = this; //<--here
    $(something).click(function(){
        that.TestFunction("Hello");
    });
};

Example on jsfiddle

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.