0

Although it is somewhat simplistic, when you execute the following code, this points to the document and you can not get an instance of Hoge.

If you make variables and functions global, there is no meaning defined in the closure, and is there any better way?

var Hoge = function() {
    this.hogehoge = 'hogehoge';
    document.addEventListener('mousedown', this.change, false);
};

Hoge.prototype = {
    change: function(e) {
        e.pageX
        console.log(this.hogehoge); // undefined
    }
};

let hoge = new Hoge();

I expect the output of console.log to be 'hogehoge', but the actual output is undefined.

salud
  • 103
  • 1
  • 1
  • 8

1 Answers1

0

You are calling this.change in outer context, you need to bind this like this.change.bind(this) to make this context remain the same as you have while clicking.

var Hoge = function() {
    this.hogehoge = 'hogehoge';
    document.addEventListener('mousedown', this.change.bind(this), false);
};

Hoge.prototype = {
    change: function(e) {
        e.pageX;
        console.log(this.hogehoge); // undefined
    }
};

let hoge = new Hoge();

For more information, Read how this gets its context here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Vishal Kumar
  • 330
  • 1
  • 9