Created
January 2, 2012 17:29
-
-
Save spolu/1551451 to your computer and use it in GitHub Desktop.
functional inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* method(that, name, method, _super) | |
* Adds a method to the current object denoted by that and preserves | |
* _super implementation (see Crockford) | |
*/ | |
method = function(that, name, method, _super) { | |
if(_super) { | |
var m = that[name]; | |
_super[name] = function() { | |
return m.apply(that, arguments); | |
}; | |
} | |
that[name] = method; | |
}; | |
var A = function(spec, my) { | |
my = my || {}; | |
var _super = {}; | |
my.counter = spec.init || 10; | |
// public | |
var test; | |
// private | |
var work; | |
var that = {}; | |
work = function() { | |
my.counter++; | |
console.log('work A called'); | |
}; | |
test = function() { | |
work(); | |
console.log('test A called: ' + my.counter); | |
}; | |
method(that, 'test', test, _super); | |
return that; | |
}; | |
var B = function(spec, my) { | |
my = my || {}; | |
var _super = {}; | |
// public | |
var test; | |
var that = A(spec, my); | |
test = function() { | |
_super.test(); | |
console.log('test B called: ' + my.counter); | |
}; | |
method(that, 'test', test, _super); | |
return that; | |
}; | |
ar a = A({init: 20}); | |
a.test(); | |
var b = B({}); | |
b.test(); | |
var c = B({init: 30}); | |
c.test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment