Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inherit class methods #26

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/p.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ var P = (function(prototype, ownProperty, undefined) {
}
}

// extend class methods
for (var name in _superclass) {
if (ownProperty.call(_superclass, name)
// don't overwrite already overwritten functions
&& typeof C[name] !== 'function'
// only extend functions
&& typeof _superclass[name] === 'function'
) {
C[name] = _superclass[name];
}
}

// if no init, assume we're inheriting from a non-Pjs class, so
// default to using the superclass constructor.
if (!('init' in proto)) proto.init = _superclass;
Expand Down
18 changes: 17 additions & 1 deletion test/p.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,10 @@ describe('P', function() {

describe('inheritance', function() {
// see examples/ninja.js
var Person = P(function(person) {
var Person = P(function(person, obj, klass) {
person.init = function(isDancing) { this.dancing = isDancing };
person.dance = function() { return this.dancing };
klass.party = function(type) { return type + '-Party' };
});

var Ninja = P(Person, function(ninja, person) {
Expand All @@ -86,6 +87,21 @@ describe('P', function() {
it('inherits methods (also super)', function() {
assert.equal(false, ninja.dance());
});

it('inherits class methods', function() {
assert.equal('Slumber-Party', Person.party('Slumber'));
assert.equal('Slumber-Party', Ninja.party('Slumber'));
});

it('inherited class methods can be extended', function() {
assert.equal('Slumber-Party', Person.party('Slumber'));
var Girly = P(Person, function(girly, person, klass, superklass) {
klass.party = function() {
return superklass.party('Slumber');
}
});
assert.equal('Slumber-Party', Girly.party('DnB'));
});
});

describe('inheriting non-pjs classes', function() {
Expand Down