开发者

javascript variable scope across functions jQuery involved

开发者 https://www.devze.com 2023-03-15 14:33 出处:网络
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.

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;//n开发者_运维技巧ot 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.


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.


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消