Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

jquery - Javascript get reference to parent object/class from event handler

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...