Permalink
Browse files

Use BareConstructor to make the subclass prototype

So that the subclass's initializer is never called, even if it's not a
pjs class.
  • Loading branch information...
1 parent 536434a commit 7a0366e77d7c5bc6593df45e1eda5c86255399cc @jneen committed Jan 28, 2013
Showing with 23 additions and 6 deletions.
  1. +9 −6 src/p.js
  2. +14 −0 test/p.test.js
View
@@ -3,6 +3,9 @@ var P = (function(prototype, ownProperty, undefined) {
function isObject(o) { return typeof o === 'object'; }
function isFunction(f) { return typeof f === 'function'; }
+ // a function that gets reused to make uninitialized objects
+ function BareConstructor() {}
+
function P(_superclass /* = Object */, definition) {
// handle the case where no superclass is given
if (definition === undefined) {
@@ -29,18 +32,18 @@ var P = (function(prototype, ownProperty, undefined) {
// same as C, so that instances of C.Bare are also instances of C.
// New objects can be allocated without initialization by calling
// `new MyClass.Bare`.
- function Bare(){}
+
+ function Bare() {}
C.Bare = Bare;
- // Set up the prototype of the new class. Note that this resolves
- // to `new Object` if the superclass isn't given.
- var proto = Bare[prototype] = C[prototype]
- = new (_superclass.Bare || _superclass);
+ // Set up the prototype of the new class.
+ var _super = BareConstructor[prototype] = _superclass[prototype];
+ var proto = Bare[prototype] = C[prototype] = new BareConstructor;
// other variables, as a minifier optimization
- var _super = _superclass[prototype];
var extensions;
+
// set the constructor property on the prototype, for convenience
proto.constructor = C;
View
@@ -84,6 +84,20 @@ describe('P', function() {
});
});
+ describe('inheriting non-pjs classes', function() {
+ function IdiomaticClass() {
+ this.initialized = true;
+ }
+
+ IdiomaticClass.prototype.initialized = false;
+
+ it('inherits without calling the constructor', function() {
+ var MySubclass = P(IdiomaticClass, {});
+ assert.equal(false, MySubclass.prototype.initialized);
+ assert.equal(true, MySubclass().initialized);
+ });
+ });
+
describe('inheriting builtins', function() {
describe('Error', function() {
var MyError = P(Error, {});

4 comments on commit 7a0366e

Contributor

laughinghan replied Mar 17, 2013

wait, so aren't the .Bare's completely unused now? What's the point of having .Bare on all Pjs classes if you're gonna use a global BareConstructor (which seems named rather unfortunately similarly to Bare, btw) when subclassing? :D

Contributor

laughinghan replied Mar 17, 2013

whoops I'm silly, Bare is used in C

Contributor

laughinghan replied Mar 17, 2013

but really, can we rename BareConstructor? Bare is totally also a constructor

Owner

jneen replied Mar 17, 2013

Yeah, if you can think of a better name, though, that'd be awesome :)

Please sign in to comment.