【问题标题】:Calling class methods within jQuery function在 jQuery 函数中调用类方法
【发布时间】:2010-07-29 16:47:52
【问题描述】:

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

【问题讨论】:

  • 如果您粘贴一个短代码 sn-p 可能会有所帮助。

标签: javascript jquery


【解决方案1】:

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

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

更多方法请参见this answer

【讨论】:

  • @Tramp - 不客气。但请注意,这仍然是一种 hacky 方法。而是使用jQuery.proxy,甚至更好的是现在包含在标准中的bind 方法。如果在某些浏览器中不可用,很容易定义一个 - stackoverflow.com/questions/3018943/…
  • 也许这是“最好的方法”,但我认为它的可读性最高且代码更少。
【解决方案2】:

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

Anurag 有一个完美的例子。

另外两种方式是 jQuery Proxy 类(在其他答案中提到)和“应用”函数

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

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"));


};

【讨论】:

    猜你喜欢
    • 2010-12-16
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2013-03-08
    • 1970-01-01
    相关资源
    最近更新 更多