Martin
Martin

Reputation: 1822

javascript variable scope across functions jQuery involved

Here is what i cannot get to work - in mouseMove this.mouseX is undefined. I need the mouseX and mouseY (e.pageX in code) from mousemove event.

function myClass () {
    var mouseX=x;
    var mouseY=y;
    $(document).mousemove(this.mouseMove);
}
myClass.prototype.mouseMove = function(e){
    this.mouseX=e.pageX;//not a good idea but you can alert this
}
var a=new myClass();

Can i get that event passed to the supposed class instance or there is no way to get it done?

I should also mention i am trying to avoid global scope variables here.

Upvotes: 0

Views: 264

Answers (4)

Felix Kling
Felix Kling

Reputation: 816324

Two three things:

var mouseX only declares a variable local to the myClass function. You have to declare a property of the instance with this.mouseX (this refers to the current instance):

function myClass () {
    this.mouseX=x;  // where do x and y come from?
    this.mouseY=y;
    //...
}

Secondly, make sure you pass x and y as parameters to the constructor. Otherwise you will get an error (if they are not defined in higher scope, but that does not seem useful to me).

Thirdly, if you just pass this.mouseMove as event handler, inside the event handler, this will refer to window and not to the myClass instance. Use $.proxy to set the context of the callback explicitly:

function myClass(x, y) {
    this.mouseX=x;
    this.mouseY=y;
    $(document).mousemove($.proxy(this.mouseMove, this));
}

I suggest to read MDC - Working with objects.

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

function myClass () {
    this.mouseX=x;
    this.mouseY=y;
    $(document).mousemove(this.mouseMove);
}
myClass.prototype.mouseMove = function(e){
    this.mouseX=e.pageX;//not a good idea but you can alert this
}
var a=new myClass();

You need to use the this keyword and not var to instantiate in the constructor

Upvotes: 0

Mike
Mike

Reputation: 1

Try:

function myClass (x,y) {
    var mouseX=x;
    var mouseY=y;
    var $this = this;

    $(document).mousemove(function(){$this.mouseMove()});
}
myClass.prototype.mouseMove = function(e){
    this.mouseX=e.pageX;//not a good idea but you can alert this
}
var a=new myClass();

Upvotes: 0

nrabinowitz
nrabinowitz

Reputation: 55688

When you pass a method like this.mouseMove as a callback function, it's no longer tied to the instance - so this will be the global object. To fix the scope, you can pass the instance in a closure, like so:

function myClass (x,y) {
    var mouseX=x;
    var mouseY=y;
    var that = this;
    $(document).mousemove(function() { that.mouseMove() });
}

Upvotes: 0

Related Questions