title: Class.create and this keyword
body: <p>I'm trying to use the <strong>Class</strong> methods of prototype.js to manage my object hierarchy on my current project, but I have some trouble with the <strong>this</strong> keyword in conjonction with <strong>Class.create</strong>.</p>
  
  <p>Here is a piece of old-fashioned plain js code to create inheritance:</p>
  
  <pre><code>var Super1 = function () {
      this.fu = "bar";
  }
  
  var Sub1 = function () {
      this.baz = "bat";
      this.f = function (e) {
          alert("Sub1:"+this.fu+this.baz);
      }.bindAsEventListener(this);
      document.observe("click", this.f);
  };
  Sub1.prototype = new Super1();
  new Sub1();
  </code></pre>
  
  <p>And here is my first attempt at mimicking this with <strong>Class.create</strong>:</p>
  
  <pre><code>var Super2 = Class.create({
      fu: "bar"
  });
  
  var Sub2 = Class.create(Super2, {
      baz: "bat",
      f: function (e) {
          alert("Sub2:"+this.fu+this.baz);
      }.bindAsEventListener(this),
      initialize: function () {
          document.observe("click", this.f);
      }
  });
  new Sub2();
  </code></pre>
  
  <p>So far so good... But of course it doesn't work: <strong>f</strong> is bound to <strong>window</strong>, not to the object created with <strong>new</strong>. The only way I found is:</p>
  
  <pre><code>var Super3 = Class.create({
      fu: "bar"
  });
  
  var Sub3 = Class.create(Super3, {
      baz: "bat",
      f: function (e) {
          alert("Sub3:"+this.fu+this.baz);
      },
      initialize: function () {
          this.f = this.f.bindAsEventListener(this);
          document.observe("click", this.f);
      }
  });
  new Sub3();
  </code></pre>
  
  <p>But it's really inelegant. How am I supposed to handle this?</p>
  
  <p>edit (to reply to Colin):</p>
  
  <ul>
  <li><p>I need to bind <strong>f</strong> itself, so that I can call <strong>stopObserving</strong> on <strong>f</strong> (see <a href="http://prototypejs.org/api/event/stopObserving" rel="nofollow noreferrer">http://prototypejs.org/api/event/stopObserving</a>)</p></li>
  <li><p>I still need <strong>bindAsEventListener</strong> every time I need <strong>this</strong> inside the listener, since by default <strong>this</strong> is the element that fires the event (see <a href="http://prototypejs.org/api/event/observe" rel="nofollow noreferrer">http://prototypejs.org/api/event/observe</a>)</p></li>
  <li><p>I'm still waiting for an anwser on the googlegroup :) I kind of posted here to see whether I can get a faster answer via S.O.</p></li>
  <li><p>I could (and probably should) use <strong>bind</strong> instead of <strong>bindAsEventListener</strong>. I used the latter to make it clear that I'm getting a listener. It doesn't change the fact that the binding procedure is inelegant.</p></li>
  </ul>