Javascript从事件处理程序中获取对父对象

Javascript从事件处理程序中获取对父对象

本文介绍了Javascript从事件处理程序中获取对父对象/类的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类(或包含函数的对象;我听说没有像JavaScript类一样的东西),名为Foo,带有附加到点击事件的事件处理程序。当调用事件处理程序时,我想修改我的类Foo的属性。通常,我将使用 this 关键字,但在事件处理程序中, this 引用设置为引用html元素。这是我的代码:

  function Foo(){

this.num = 0;
$('element')。click(this.eventHandler); // jQuery将onclick事件附加到我的元素。

this.eventHandler = function(){
this.num ++; //这不工作。
//通常,this指的是我的Foo实例,
//但是作为事件处理程序,this指的是html元素。
}
}

所以我的问题是:我的实例Foo进入我的事件处理程序,以便我可以修改其属性(如 num )?

  function Foo(){
var _self = this;
this.num = 0;

$('element')。click(this.eventHandler); // jQuery将onclick事件附加到我的元素。

this.eventHandler = function(){
_self.num ++;
}
}

使用引用 _self =此在外部范围


中定义

I have a class (or function-containing object; I've heard that there is no such thing as a Javascript class) called Foo, with an event handler that is attached to a click event. When the event handler is called, I want to modify a property of my class Foo. Normally, I would use the this keyword, but in the event handler, the this reference is set to the reference to the html element. Here is my code:

function Foo() {

    this.num=0;
    $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element.

    this.eventHandler=function() {
        this.num++;// This doesn't work.
        // Normally, "this" would refer to my instance of Foo,
        // but as an event handler, "this" refers to the html element.
    }
}

So my question is: how do I get a reference to my instance of Foo into my event handler so that I can modify its properties (like num)?

解决方案
function Foo() {
    var _self = this;
    this.num=0;

    $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element.

    this.eventHandler=function() {
        _self.num++;
    }
}

use a reference _self = this defined in the outer scope

这篇关于Javascript从事件处理程序中获取对父对象/类的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:17