/PTClass

A standalone version of prototype's Class interface

Primary LanguageJavaScript

It's Class.create() from prototype, but standalone. Yep, that's it.

Version 1.7 from https://github.com/sstephenson/prototype

View the docs at http://www.prototypejs.org/learn/class-inheritance (the new way)

Unminified: 9.11k
Minified: 2.06k
Minified+gzip: <1.7k

What's not to love?




PTClass JS Inheritance Findings

"When a member is sought and it isn't found in the object itself, then it is taken from the object's constructor's prototype member."
--Douglas Crockford

      // Classes
      var A = Class.create( {
        id: "A",
        initialize: function () {
          this.foo = function () {
            return "A - PRIVILEGED, from " + this.id;
          };
        },
        foo: function () {
          return "A - PROTO, from " + this.id;
        }
      } );
 
 
      var B = Class.create( A, {
        id: "B",
        initialize: function($super){
          //$super();
        },
        foo: function ($super) {
          return $super() + " :: B - PROTO, from " + this.id;
        }
      });
 
 
 
      var a = new A();
      console.log(a.yell());
 
      var b = new B();
      console.log(b.yell());

1. For A.foo and A.prototype.foo, instance a.foo() calls the privileged method A.foo.

2. If B inherits from A and we create method B.prototype.foo, calling instance b.foo() calls _the privileged method A.foo_. Since B inherits from A which has the privileged method foo, that gets called before the prototype is searched.

3. Now if we create an empty initialize method on B, this seems to break the privileged inheritance chain, since calling B.foo() really calls B.prototype.foo. Furthermore, $super within B.prototype.foo references A.prototype.foo(), not A's privileged method. $super seems to always reference the prototype method.

4. Next, adding $super() within B's initialize method, restores the inheritance chain as in case #2 above.

5. When called from b.foo(), The this keyword points to the instance b even from within the privileged method at A.foo. "this" always refers to the instance.

6. Adding a privileged method onto B overrides the same method on A – B.foo trumps A.foo – but using $super to call the parent method won't work.

7. Calling $super() from within B.initialize after declaring B.foo there will override B.foo with A.foo. Conversely, declaring B.foo after calling $super() will override A.foo.

8. Privileged methods may only consist of private attribute getters, which can then be used by public methods, which in turn can easily be extended.