marcosh marcosh - 4 years ago 112
Javascript Question

Retrieve origina context from callback

I have a JavaScript class with two methods like this.

var MyObject = function () {};

MyObject.prototype = {
open: function () {
var self = this;
console.log(self);

$('#a').click('', self.other);
},
other: function () {
console.log(this);
}
};

var myobject = new MyObject;

myobject.open();


In the
console.log
in the
other
function,
this
is the HTML node that the event listens to and not the
MyObject
object as in the
open
function.

How can I retrieve the
MyObject
object from the function
other
when used as a callback?

Answer Source

You can use $.proxy passing the this context as 2nd parameter:

var MyObject = function () {};

MyObject.prototype = {
    open: function () {
        $('#a').click($.proxy(this.other, this));
    },
    other: function () {
        console.log(this);
    }
};

var myobject = new MyObject;

myobject.open();

When clicking on #a the MyObject.other() function will be called with a this instance referring to MyObject.

JSFIddle with code in action

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download