0

Consider the following JavaScript class, property, and method:

function Foo() {
    this.data = 123;
}

Test.prototype.foo = function() {
    $("body").append($("<div>")
        .text("Hello World!")
        .click(function () {
            alert("Data: " + this.data);
        })
    );
}

var Bar = new Foo();
Bar.foo();

Why is the property data undefined in the alert box? How can "this" be referenced, as pointed to the Foo class and not the jQuery div element?

2 Answers 2

7

The problem is that this inside the event handler refers to the element targeted by the handler; you can use a closure variable to hold the object reference like

Test.prototype.foo = function () {
    var self = this;
    $("body").append($("<div>")
        .text("Hello World!")
        .click(function () {
        alert("Data: " + self.data);
    }));
}

Or you can pass a custom execution context to the handler method using methods like $.proxy()/Function.bind()

Test.prototype.foo = function () {
    $("body").append($("<div>")
        .text("Hello World!")
        .click($.proxy(function () {
        alert("Data: " + this.data);
    }, this)));
}
Sign up to request clarification or add additional context in comments.

Comments

1

The reason is simple. Since you are accessing this within the click event callback of jquery element, this points to the element on which the event has occurred.

You can change add slight change in the code to make it work, check the jsfiddle below.

http://jsfiddle.net/satyagupta/efohyekq/

Test.prototype.foo = function() {
    var data = this.data;              // <--- Add this line
    $("body").append($("<div>")
        .text("Hello World!")
        .click(function () {
            alert("Data: " + data);
        })
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.