开发者

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, whic开发者_开发问答h 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜