Kyle
Kyle

Reputation: 151

JavaScript Scope Clarification

I've been reading just about every article I can get my hands on about JavaScript scope to better understand it. I'd like to perfectly understand it by the end. I'm currently reading this article: http://www.digital-web.com/articles/scope_in_javascript/ and I've just finished reading the "Complications" section (a little more than halfway down) and thought it was very helpful, but not quite clear enough.

It uses the following code and considers the onclick behavior of the_button:

function BigComputer(answer) { 
  this.the_answer = answer; 
  this.ask_question = function () { 
   alert(this.the_answer); 
  } 
} 

function addhandler() { 
  var deep_thought = new BigComputer(42), 
   the_button = document.getElementById('thebutton'); 

  the_button.onclick = deep_thought.ask_question; 
} 

window.onload = addhandler;

The article states ... an event handler[,] runs in a different context than when it’s executed as an object method. So, if I'm to understand correctly, then the call to the ask_question method in context of the script's object method is deep_thought.ask_question, making this deep_thought. But when an event in the DOM is triggered, then the call chain changes to DOMelement.eventHandler.deep_thought.ask_question making this DOMelement?

Upvotes: 0

Views: 93

Answers (1)

Esteban Felix
Esteban Felix

Reputation: 1561

That is correct! 'this' in event handlers is the element you bound to. In this case it would be the_button. The alert would be 'undefined' as the_button has no the_answer property.

You can see an example at: http://jsfiddle.net/zG7KR/

See what this outputs:

this.ask_question = function () { 
     alert(this.the_answer);
};

Upvotes: 2

Related Questions