简体   繁体   English

在 jQuery 内调用 class 方法 function

[英]Calling class methods within jQuery function

So I have some javascript class and in one method I use jQuery to bind function to click event.所以我有一些 javascript class 并且在一种方法中我使用 jQuery 将 function 绑定到点击事件。 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.在这个 function 中,我需要调用这个 class 的其他方法。在通常的 js function 中,我是通过"this.method_name()"完成的,但在这里,我猜,jQuery 重新定义了 "this" 指针。

jQuery doesn't redefine the this pointer, but that's how JavaScript functions work in general. jQuery没有重新定义this指针,但这就是JavaScript函数的工作原理。 Store a reference to the this pointer under a different name, and use that. 以不同的名称存储对this指针的引用,并使用它。

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

See this answer for more approaches. 有关更多方法,请参阅此答案

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类(在其他答案中提到)和'apply'函数

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


};

In addition to the possibility of temporarily storing a reference to this ( self = this , see Anurag's answer), since ES6 it is possible to use arrow functions for this problem.除了暂时存储对this的引用的可能性( self = this ,请参阅 Anurag 的回答),因为 ES6 可以使用箭头函数来解决这个问题。 These have no "own" this .这些没有“自己的” this This means that the "usual" object-related this can be accessed again within an arrow function within an event handler:这意味着可以在事件处理程序中的箭头 function 中再次访问与“通常”对象相关的this

$("selector").click(() => {
    this.method_name();
});

Further information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions?retiredLocale=de#cannot_be_used_as_methods更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions?retiredLocale=de#cannot_be_used_as_methods

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions?retiredLocale=de#using_call_bind_and_apply https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions?retiredLocale=de#using_call_bind_and_apply

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM