Note that there are some explanatory texts on larger screens.

plurals
  1. POJavaScript Scope Clarification
    primarykey
    data
    text
    <p>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: <a href="http://www.digital-web.com/articles/scope_in_javascript/" rel="nofollow">http://www.digital-web.com/articles/scope_in_javascript/</a> 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.</p> <p>It uses the following code and considers the <code>onclick</code> behavior of <code>the_button</code>:</p> <pre><code>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; </code></pre> <p>The article states <code>... an event handler[,] runs in a different context than when it’s executed as an object method.</code> So, if I'm to understand correctly, then the call to the <code>ask_question</code> method in context of the script's object method is <code>deep_thought.ask_question</code>, making <code>this</code> <code>deep_thought</code>. But when an event in the DOM is triggered, then the call chain changes to <code>DOMelement.eventHandler.deep_thought.ask_question</code> making <code>this</code> <code>DOMelement</code>?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload