Reputation: 1424
SOLVED
Assigning the prototypes at the very bottom was overwriting my previous declarations. Thanks to Guffa for the quick answer.
I've been browsing around and kind find a good answer, mods, if this is a doop i'm sorry.
To the code.. I have three functions, one, two , and three respectively. I would like three to inherit from two, and two from one. The prototype of three should reach all the way back down to one, which it does. I can call methods from one while i'm in an instance of three. But i'm unable to call methods from two.
Here's an example.
function one () {
this.version = 1;
};
one.prototype.one = function () {
return 'I live on the one class';
};
function two () { // extends one
this.version = 2;
};
two.prototype.two = function () {
return 'I live on the two class';
};
function three () { // extends two
this.version = 3;
};
three.prototype.three = function () {
return 'I live on the three class';
};
two.prototype = Object.create(one.prototype);
three.prototype = Object.create(two.prototype);
var x = new three();
x.one // -> 'I live on the one class!'
x.two // -> undefined
x.three // -> undefined
When I call x.one, I get the expected output of 'i live on the one class'. But x.two is undefined. When I look at the prototype chain, there are no methods/properties on two's chain at all. Only the prototype from one is accessible.
My brain is crying.
EDIT I hadn't tried x.three yet, but it is also undefined. Maybe the way I am inheriting is overwriting the prototypes instead of sharing? Although if that were the issue, I feel like I would have access to two and not one. I'm not sure why I have access to the root class, but none in between, not even on the instance that was called. It's as if three is just a reference to one.
Upvotes: 2
Views: 100
Reputation: 700362
You are replacing the prototype of two
and three
after adding methods to them. The prototype chain works fine, but the two
and three
methods aren't in the prototypes after you replaced them.
Replace the prototypes before adding methods to them:
function one () {
this.version = 1;
};
one.prototype.one = function () {
return 'I live on the one class';
};
function two () { // extends one
this.version = 2;
};
two.prototype = Object.create(one.prototype);
two.prototype.two = function () {
return 'I live on the two class';
};
function three () { // extends two
this.version = 3;
};
three.prototype = Object.create(two.prototype);
three.prototype.three = function () {
return 'I live on the three class';
};
var x = new three();
// Show values in snippet
document.write(x.one() + '<br>'); // -> 'I live on the one class'
document.write(x.two() + '<br>'); // -> 'I live on the two class'
Upvotes: 2