Skip to content

Commit

Permalink
Add oop module to allow object oriented programming with correct inhe…
Browse files Browse the repository at this point in the history
…ritance
  • Loading branch information
Manuel Quiñones committed Jul 18, 2013
1 parent cd149d4 commit 508ed9b
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
23 changes: 23 additions & 0 deletions oop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
define(function () {

// Source: http://stackoverflow.com/a/4389429/1178541

var oop = {};

// This is a constructor that is used to setup inheritance without
// invoking the base's constructor. It does nothing, so it doesn't
// create properties on the prototype like our previous example did

function surrogateCtor() {}

oop.extend = function (base, sub) {
// Copy the prototype from the base to setup inheritance
surrogateCtor.prototype = base.prototype;
// Tricky huh?
sub.prototype = new surrogateCtor();
// Remember the constructor property was set wrong, let's fix it
sub.prototype.constructor = sub;
}

return oop;
});
57 changes: 57 additions & 0 deletions test/oopSpec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
define(["sugar-web/oop"], function (oop) {

describe("oop", function () {

Person = function (name) {
this.name = name;
};

Person.prototype.sayHi = function () {
return "Hi! I'm " + this.name;
};

Person.prototype.tellMore = function () {};

SuperHero = function (name, power) {
Person.call(this, name);
this.power = power;
};

oop.extend(Person, SuperHero);

SuperHero.prototype.tellMore = function () {
return Person.prototype.sayHi.call(this) +
", and I can " + this.power;
};

var bob = new Person("Bob");
var superman = new SuperHero("Superman", "fly");

it("should consider instanceof", function () {
expect(bob instanceof Person).toBe(true);
expect(superman instanceof Person).toBe(true);
expect(superman instanceof SuperHero).toBe(true);
});

it("should pass parameters to the parent constructor", function () {
expect(bob.name).toBe("Bob");
expect(superman.name).toBe("Superman");
});

it("should add new propierties", function () {
expect(bob.power).toBeUndefined();
expect(superman.power).toBe("fly");
});

it("should call parents methods", function () {
expect(bob.sayHi()).toBe("Hi! I'm Bob");
expect(superman.sayHi()).toBe("Hi! I'm Superman");
});

it("should redefine parents methods", function () {
expect(bob.tellMore()).toBeUndefined();
expect(superman.tellMore()).toBe("Hi! I'm Superman, and I can fly");
});
});

});

0 comments on commit 508ed9b

Please sign in to comment.