javascript 在 jQuery 函数中调用类方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3365005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:58:44  来源:igfitidea点击:

Calling class methods within jQuery function

javascriptjquery

提问by Tyth

So I have some javascript class and in one method I use jQuery to bind function to click event. And within this function I need to call other methods of this class. In usual js function I did it through "this.method_name()", but here, I guess, jQuery redefines "this" pointer.

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

回答by Anurag

jQuery doesn't redefine the thispointer, but that's how JavaScript functions work in general. Store a reference to the this pointer under a different name, and use that.

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

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

See this answerfor more approaches.

有关更多方法,请参阅此答案

回答by CPettit

There are a few different ways to do this.

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

Anurag has a perfect example of one.

Anurag 有一个完美的例子。

Two other ways are the jQuery Proxy class (Mentioned in other answers) and the 'apply' function

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

Now lets create an object with click events:

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

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


};