JS inheritance done in a fun way
JavaScript
/*
we start with the basics - let's have a function A
*/
function A(name) {
this.name = name;
}
A.prototype.foo = function() {
console.log(this.name);
};
A.prototype.bar = function() {
console.log("BAR!");
}
/*
now - let's say we want function B to inherit behavior from A.
Since JS is so polymorphic - if all we want is to lend behavior - we can do this:
*/
function B(name) {
//JS native way of calling super's constructor
A.call(this, name);
}
B.prototype.foo = function() {
//JS native way of calling other objects onto your object
console.log("my name is:" + A.prototype.foo.call(this));
}
/*
this is all nice and well, as long as we allways intend to borrow methods. But, if we want to inherit
the prototype, it requires some proto copying (at least as long as we stay standard and don't do
__proto__ voodoo
*/
//since we want to be able to create a new link in the prototype chain, we have to call "new"
//however, we don't want to call A's constructor logic, just copy it's prototype, so we create a temp
//constructor
function F() {};
F.prototype = A.prototype;
B.prototype = new F();
B.prototype.foo = function() {
//JS native way of calling other objects onto your object
console.log("my name is:" + A.prototype.foo.call(this));
}
/*
now, all this is a bit too much without automation.
Calling A.prototype.foo is very verbose,
And creating a temp function each time, referencing the protoype etc is also too verbose.
So - lets have this nice little method that does all these things for us:
*/
function inherit(obj /*target object/function*/ ,
parent /*parent*/ ,
props /*we might as well have some fun and dump all the B.prototype.foo verbosity as well*/ ) {
var proto = parent.prototype,
prop;
function F() {}
F.prototype = parent;
obj.construct = function() {
return parent.apply(obj, arguments);
}
obj.parent = function(name, args)...