0
function(){
"use strict";

var FileCrop = function() {
    this.init();
};

var p = FileCrop.prototype = lx.BaseClass.extend(lx.BaseClass);
p.BaseClass_init = p.init;


p.test = 'test';

p.init = function() {
    // Super
    this.BaseClass_init();
    // Init
    this.ready();

};

p.ready = function() {

    this._initEvents();

};
p._initEvents = function() {
    console.log(this.test); //this works

    this.cropBox.on('mousedown', this.mouseDown);
    $(document).on('mouseup', this.mouseUp);

};

p.mouseDown = function(e) {

console.log(this.test);//this is undefined
    $(document).on('mousemove', this.mouseMove);


};

 p.mouseMove = function(e) {
     console.log('mouse is moving'); //this is never called
 };


lx.FileCrop = FileCrop;
}(window));

I'm having trouble with scope and my class.

It would be great if someone could explain to me what I'm doing wrong. I'm trying to get the test variable throughout the class (in the real class its something else but this gives an easy to understand example).

I have commented on the code above where the test var logs ok and where it doesn't. I'm also having trouble with mouse move. This fails:

$(document).on('mousemove', this.mouseMove);

Whereas this works:

$(document).on('mousemove', p.mouseMove);

I was just wondering why this is the case as I am able to use 'this' on mouse down and it works.

panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

0

You need to explicitly ensure that the value of this to be used inside your event handlers is a reference to your object. That does not happen automatically when you use an expression like this.mouseDown. That gets you a reference to the function, but the relationship to the object referenced by this is not preserved.

A simple way to do that in modern JavaScript environments is

  this.cropBox.on('mousedown', this.mouseDown.bind(this));

The .bind() function returns another function, one which will call the originally desired function (your "mouseDown" function) with the value of this guaranteed to be what you request via the parameter.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • So basically before, on mouse down, it did not have a reference to my class, but now it does, so it can access all my class vars? – panthro Jun 02 '14 at 15:07
  • The key thing is that the value of `this` in a function depends only on how the function is invoked. – Pointy Jun 02 '14 at 16:05