I wrote two classes the other day, where I needed to override and call the overridden method (getQuery).
//parent
function SimpleUser() {
this.firstName = "X";
}
SimpleUser.prototype.getQuery = function(sub) {
//solution for not getting undefined variables
var that = sub || this;
var query = "first="+that.firstName;
return query;
}
//child
function User() {
//extends
this.base = SimpleUser;
//super()
this.base();
//prints "X"
console.log(this.firstName);
this.lastName = "Y";
}
//override
User.prototype.getQuery = function() {
//call parent
var query = SimpleUser.prototype.getQuery.call(this);
query += "&last="+this.lastName;
return query;
}
//prints "first=X"
console.log(new SimpleUser().getQuery());
//prints "first=undefined&last=Y" if I don't use parameter "sub"
console.log(new User().getQuery());
When I call the method “getQuery” from the sub-class, all variables in the parent are undefined. If I call them from the constructor of the sub-class, they’re fine.
I solved the problem by passing the sub-class as parameter and just checking who’s asking.
Can someone please explain to me why this happens and help me to find a better solution than what I had to do with passing the sub-class itself as a parameter?
Thank you!
Javascript doesn’t have classes. It only has objects. And objects inherits from their prototypes, which in turn inherits from their prototypes and so forth. If you want to learn more about making inheritance in javascript take a look at http://phrogz.net/js/classes/OOPinJS2.html. Though this is doable, if you want to mimic classes and class-inheritence in javascript I recommend using a framework designed for this such as MooTools.