qrikko
qrikko

Reputation: 2603

confusion, this-pointer and events in javascript

I have a javascript object which I would like to be able to handle some interactive features. It's a bit tricky to describe the scenario in a simple way so hopefully it'll not get all out of hand here.

my object looks something like

myobject = function() {
    this.initialize = function() {
        // HERE this = the myobject instance
        var test = document.createElement('div');
        test.onmousedown = this.mousedown;
    }
    this.mousedown = function(e) {
        // HERE this = the calling div-element
    }
}

So my problem is basically that this will not be an myobject instance when this.mousedown(e) is called, it will rather be the caller (if the terminology is correct?) in this case it is the div I created and put in a variable called test above.

I would like to have access to the instance on which the method is being run (as I believe that to be the mousedown method I created).

This far I have had some ideas which I have tried out:

It's all I can think of now hope it makes sence.

Upvotes: 0

Views: 92

Answers (2)

Kenneth
Kenneth

Reputation: 28737

You could create a copy when you first instantiate the object:

var myobject = function() {
    var self = this;    
    this.initialize() {
        // HERE this = the myobject instance
        var test = document.createElement('div');
        test.onmousedown = this.mousedown;
    }
    this.mousedown(e) {
        // HERE this = the calling div-element
        // use self instead of this
    }
}

Upvotes: 4

Tom Carchrae
Tom Carchrae

Reputation: 6486

The simplest solution is to make a 'self' var that you refer to in the callback:

myobject = funciton() {
    var self = this;
    this.initialize() {
        //use self to refer to myobject
        self.mousedown(e);
    }
    this.mousedown(e) {

    }
}

Upvotes: 0

Related Questions