Alesh Houdek
Alesh Houdek

Reputation: 998

Why is my method not seeing this.property?

In the code below, initializeBoard has access to the property, and the console returns 'white' when I start the script. But when I click inside the window, I get 'undefined'. What obvious thing am I missing? (Bonus: what's the search query that'd have led me to the answer without having to ask?)

var view = {

  currentMove: 'white',

  initializeBoard: function() {
    console.log(this.currentMove);
  },

  click: function(e) {
    console.log(this.currentMove);
  }
}

window.onload = function() {
  view.initializeBoard();
  document.onclick = view.click;
}

Upvotes: 1

Views: 66

Answers (1)

Quentin
Quentin

Reputation: 943142

The value of this is determined by how the function is called, not by where it is first assigned.

You are copying the (reference to the) function to document.onclick.

When the click event happens document.onclick is called. view.click is not called (even though it has the same value as document.onclick). This means that this is document not view.

Use bind if you want to create a wrapper function that calls the original function in the right context.

document.onclick = view.click.bind(view);

Upvotes: 3

Related Questions