Search code examples
javascripteventsthisanonymous-functionparent-node

Javascript "this" through different scope


Please, read and try the code below. Click on "foo" paragraph. Looking at the browser console, I don't see the expected results, while if I click on "bar", I do.

Why is that happening?

<!DOCTYPE HTML PUBLIC
  "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
  </head>
  <body>
    <div class="root">
      <div>
        <p id="foo">foo</p>
      </div>
      <p id="bar">bar</p>
    </div>
    <script type="text/javascript">
      var p_list = document.getElementsByTagName('P');
      for (var n=0; n<p_list.length; n++) {
        p_list[n].onclick = function() {
          console.log('ONCLICK - id: ' + this.id + ' - ' + getC( this ) + '\n');
        };
      }
      function getC( P ) {
        if (P.parentNode.className === 'root') {
          console.log('INSIDE FUNCTION - id: ' + P.id + ' - ' + P.parentNode);
          return P.parentNode;
        } else {
          getC( P.parentNode );
        }
      }
    </script>
  </body>
</html>

Live code: http://jsbin.com/izuleg/1/edit


Solution

  • You're just missing a return statement in your else clause. It should be:

    ...
    
    } else {
        return getC( P.parentNode );
    }
    

    Note that you're using a recursive function (a function that calls itself), so you should probably add extra precautions to make it return something in exceptional cases (such as, there is no node with class "root"), otherwise you'll get an infinite recursion, and a stack overflow error.