Permalink
Browse files

Avoid calling superclass' initializer when extending

  • Loading branch information...
1 parent 47b5d82 commit 78b19a28c2f7eb6b3ccfe0d568a12e5b5398a024 @bkeepers committed Mar 30, 2011
Showing with 38 additions and 20 deletions.
  1. +10 −0 spec/javascripts/lucid.class.spec.js
  2. +28 −20 src/lucid.class.js
@@ -35,6 +35,16 @@ describe('Lucid.Class', function () {
new Foo();
}).not.toThrow();
});
+
+ it('should not call initialize on parent class when extending', function () {
+ Foo = Lucid.Class.extend({
+ initialize: function () {}
+ });
+
+ spyOn(Foo.prototype, 'initialize');
+ Foo.extend({});
+ expect(Foo.prototype.initialize).not.toHaveBeenCalled();
+ });
});
describe('class methods', function () {
View
@@ -1,27 +1,35 @@
var Lucid;
Lucid = Lucid || {};
-Lucid.Class = function () {
-};
+// Simple inheritance patterned after http://ejohn.org/blog/simple-javascript-inheritance/
+(function () {
+ Lucid.Class = function () {
+ };
-Lucid.Class.Methods = {
- extend: function (properties) {
- var Class = function () {
- if (this.initialize) {
- this.initialize.apply(this, arguments);
- }
- };
+ var initializing = false;
- Class.prototype = _.extend(new this(), properties);
- _.extend(Class, this.Methods);
- Class.prototype.constructor = Class;
- return Class;
- },
+ Lucid.Class.Methods = {
+ extend: function (properties) {
+ var Class = function () {
+ if (!initializing && this.initialize) {
+ this.initialize.apply(this, arguments);
+ }
+ };
- include: function () {
- _.extend.apply(_, [this.prototype].concat(_.toArray(arguments)));
- return this;
- }
-};
+ initializing = true;
+ Class.prototype = _.extend(new this(), properties);
+ initializing = false;
-_.extend(Lucid.Class, Lucid.Class.Methods);
+ _.extend(Class, this.Methods);
+ Class.prototype.constructor = Class;
+ return Class;
+ },
+
+ include: function () {
+ _.extend.apply(_, [this.prototype].concat(_.toArray(arguments)));
+ return this;
+ }
+ };
+
+ _.extend(Lucid.Class, Lucid.Class.Methods);
+})();

0 comments on commit 78b19a2

Please sign in to comment.