在jQuery函数中调用类方法

时间:2010-07-29 16:47:52

标签: javascript jquery

所以我有一些javascript类,在一个方法中我使用jQuery将函数绑定到click事件。在这个函数中我需要调用这个类的其他方法。在通常的js函数中,我通过"this.method_name()"完成了它,但是在这里,我想,jQuery重新定义了“this”指针。

2 个答案:

答案 0 :(得分:9)

jQuery没有重新定义this指针,但这就是JavaScript函数的一般工作方式。以不同的名称存储对this指针的引用,并使用它。

var self = this;
$("selector").click(function() {
    self.method_name();
});

有关更多方法,请参阅this answer

答案 1 :(得分:3)

有几种不同的方法可以做到这一点。

Anurag有一个完美的例子。

另外两种方法是jQuery Proxy类(在其他答案中提到)和'apply'函数

现在让我们创建一个包含点击事件的对象:

var MyObj = function(){

this.property1 = "StringProp";

// jQuery Proxy Function
$(".selector").click($.proxy(function(){

  //Will alert "StringProp"
  alert(this.property1);
// set the 'this' object in the function to the MyObj instance


},this));


//Apply Function
//args are optional
this.clickFunction = function(arg1){
    alert(this.property1);
};

$(".selector").click(this.clickFunction.apply(this,"this is optional"));


};