Reputation: 61
I'm having an issue with prototype inheritance and I can't find out why it's not working properly.
The snippet is this:
function Field(newKey, val) {
this.key = newKey || "";
this.value = val || "";
}
Field.prototype.isEmpty = function() {
return this.value === undefined || this.value === null || this.value === "";
};
function DoubleField(newKey, val) {
this.base = Field;
this.base(newKey, val);
}
DoubleField.prototype = new Field();
DoubleField.prototype.constructor = DoubleField;
function IntegerField(newKey, val) {
this.base = DoubleField;
this.base(newKey, val);
}
IntegerField.prototype = new DoubleField();
IntegerField.prototype.constructor = IntegerField;
var f = new Field('keyfield', 'valField');
var d = new DoubleField('keydouble', 'valDouble');
var i = new IntegerField('keyinteger');
var res = f.isEmtpy();
The call to f.isEmpty is failing? Why? Calls to d.isEmpty or i.isEmpty work just fine as expected.
I cannot realize what I'm doing wrong. Any help would be much appreciated!
Upvotes: -1
Views: 91
Reputation: 1074295
You haven't said how it's failing. As I noted in a comment, at the very least there's a typo: var res = f.isEmtpy();
should be var res = f.isEmpty();
But beyond that (which I assume is just a typo in the question, not the code), note that this line in your derived constructors:
this.base = DoubleField;
...will not work as you intend. Consider the case of IntegerField
. You call new IntegerField
and it sets this.base
to DoubleField
and calls it. But the DoubleField
constructor then sets this.base
to Field
. So you have an IntegerField
instance with a base
property pointing to Field
, not DoubleField
.
You can't use instance properties to trace lineage. It works for a parent/child situation, but you run into the "grandchild" problem described above.
I recommend using one of the inheritance helper scripts out there. There are several, including my own Lineage
. These scripts help you build inheritance hierarchies, handling the plumbing for you so you can focus on building whatever it is you're trying to build. We only need them temporarily; JavaScript is getting syntactic sugar to help with this in the next version (but of course, it'll be years before we see widespread support of it, once it's actually finalized).
Upvotes: 1
Reputation: 11342
The error is in the last line of code:
var res = f.isEmtpy();//That's what you wrote
The correct is:
var res = f.isEmpty();
Upvotes: 4