0

I have the following javascript:

var testObj = function() {
    this.test1 = "123";
}


testObj.prototype = {
    myFunc: function() {
        var input = $('<input type=button value="clickme" />');
        $('body').append(input);
        input.click(function () {
            alert(this.test1);
        });
    }
}

$(document).ready( function() {
    var t = new testObj();
    t.myFunc();
});

I know why the alert statement is showing undefined, but how do I make it show the actual value of test1 variable.

jsFiddle has the sample code.

3 Answers 3

2

You can do this

http://jsfiddle.net/33Mtu/7/

myFunc: function() {
    var self = this;
    var input = $('<input type=button value="clickme" />');
    $('body').append(input);
    input.click(function () {
        alert(self.test1);
    });
},

When you say this inside the click function, this refers to the clicked item. I set self to this so you can safely use self inside the click function

Sign up to request clarification or add additional context in comments.

Comments

1

Try to create a reference to the object to access it, this on an event refers to the sender:

 myFunc: function() {
        var input = $('<input type=button value="clickme" />');
        $('body').append(input);
        var obj = this;
        input.click(function () {
            alert(obj.test1);
        });

Comments

0
    var testObj = function() {
    test1 = "123";
}


testObj.prototype = {
    myFunc: function() {
        var input = $('<input type=button value="clickme" />');
        $('body').append(input);
        input.click(function () {
            alert(test1);
        });
    }
}

$(document).ready( function() {
    var t = new testObj();
    t.myFunc();
});

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.