0

I'm trying to call a this method in my class. When I do that, I get an error saying:

Uncaught TypeError: this.logMe is not a function

I tried removing this but it still had an error. Here's my code:

function Logger() {
    this.logMe = function() {
    console.log('Log a Message');
  };

  window.addEventListener('click', function() {
        this.logMe();
  });
}

var hello = new Logger();

What am I doing wrong and how can I fix it?

Jessica
  • 9,379
  • 14
  • 65
  • 136

4 Answers4

1

Your this is for an anonymous method instead of Logger

function() {
    // this is about this anonymous method instead of Logger
    this.logMe();
}

You can try to use window.addEventListener('click', this.logMe); to make you expect.

function Logger() {
    this.logMe = function() {
    console.log('Log a Message');
  };

  window.addEventListener('click', this.logMe);
}

var hello = new Logger();
D-Shih
  • 44,943
  • 6
  • 31
  • 51
0

an alternate pattern (passing some message would probably make sense):

var Logger = {
  log: function(msg) {
      if(typeof(msg) != 'undefined') {
          console.log(msg);
      }
  }
};

window.addEventListener('click', function() {
   Logger.log('Log a Message');
});
Martin Zeitler
  • 1
  • 19
  • 155
  • 216
-1

function Logger() {
    this.logMe = function() {
    console.log('Log a Message');
  };

  window.addEventListener('click', () => this.logMe(), false);
}

var hello = new Logger();

Look at this : https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

ghuntheur
  • 392
  • 1
  • 5
  • 17
-2

You need to remove this and it will work as expected.

function Logger() {
  logMe = function() {
    console.log('Log a Message');
  };

  window.addEventListener('click', function() {
        logMe();
  });
}

var hello = new Logger();
Raj
  • 505
  • 1
  • 6
  • 14