简体   繁体   中英

How do I access member variables inside of an event in Javascript

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.

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

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);
        });
    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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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