user1904218 user1904218 - 11 months ago 43
Javascript Question

Accessing object properties in listener method

Let's say I have the following code:

var Obj = function() { = 1;
this.arr = [...] // array containing elements we want to add event listeners to
for (...) {
this.arr[i].addEventListener("click", this.listener, false);

Obj.prototype.listener = function() {
console.log( ); // DOES NOT WORK! *this* does not point to Obj.
var a = new Obj();

How do I access object properties (and methods) within a listener? I would assume I'd need to pass it as a parameter? Is the way I'm going about this structurally wrong?

Answer Source

When the function is called as an event listener, the context (this) is changed to something other that the object itself.

To resolve this, manually bind the context to the object instance in the constructor using bind(). This way, this will always point to the object instance, independent of the calling context:

var Obj = function() { = 'foo';
  this.listener = this.listener.bind(this);

Obj.prototype.listener = function() {

var a = new Obj();{});