When I run this code:
function foo() {
console.log("foo");
var self = this;
this.a = function() {
return arguments.length == 0 ? self.b : (self.b = arguments[0]);
};
};
function bar() {
};
bar.prototype = new foo();
var a = new bar();
var b = new bar();
console.log(a.a());
b.a(true);
console.log(a.a());
I get the following output: foo, undefined, true
What I do not understand is how the object returned by the constructor function foo somehow manages to allocate a new memory location for b. I was totally expecting the last output to be true because I only get 1 foo output.
That this works is great, but it feels too much like magic.
My problem really here is that I’d like to setup an initialization order (or chain). What I’ve realized is that foo cannot take any arguments, because it’s only called once, to provide a base (or template of sorts).
I’d like to devise a really simple schema where foo has parameters that has to be passed from bar to foo (because bar inherits foo). I’m fine with something like calling foo.apply(this, arguments) from bar but the call to set the prototype has to be done without arguments, what I need is a fluent way to somehow tell the two apart.
But I really don’t want to build an entire service around creating objects that allow some kind of inheritance, the only thing I really care about is constructing the objects, correctly…
On a side note, you’re sometimes using
selfand sometimes usingthis… personally, I’d be more consistent. I like to usethatbecausethiscan be confusing andselfis part of the BOM, but it’s just a matter of taste.Try parasitic inheritance:
… here the inheritance behaves in a more classically, explicitly invoking a parent constructor when the constructor is called.