I've got a BaseService for easy interaction with my server-side API, and I'd like to "subclass" it for specific API resources. What better way than to directly inherit from the BaseService which does all the hard work?
So, I've got it set up, and it works, however I'm not entirely sure I am doing it the right way, as I've read that there are multiple types of inheritance in JS. Here's a link to some code I found that does it different ways: https://github.com/roblevintennis/Testing-and-Debugging-JavaScript/blob/master/code/objects/lib/js_inheritance.js
This is the way I am doing it. I've left function bodies out for brevity.
The BaseService
, that my implementations will inherit from.
BaseService.prototype.get = function (resource, data, parameterOverrides) {
return aPromisedLandOfDragons();
};
BaseService.prototype.post = function (resource, data, parameterOverrides) {
return aPromisedLandOfDragons();
};
BaseService.prototype.put = function (resource, data, parameterOverrides) {
return aPromisedLandOfDragons();
};
BaseService.prototype.destroy = function (resource, data, parameterOverrides) {
return aPromisedLandOfDragons();
};
function BaseService(resource) {
this.apiEndpoint = "/api/" + resource + "/";
}
Here is an implementation that can directly use the BaseService
, passing in the API resource to the constructor.
AccountService.prototype = new BaseService("Accounts");
AccountService.prototype.getAll = function(searchString) {
// Uses the BaseService method. Lovely!
return this.get(null, {
searchString: searchString || ""
});
};
function AccountService() {
}
So, my question is (and hoping it won't be closed due to too localized): Is this a good way of doing inheritance in JavaScript? Does it have any performance impacts that can be drastically improved?
As an aside: If I wanted to directly override a method from the base class, e.g .get
, is it possible to do that, while still being able to call the base class' implementation?
P.S: I know that technically there is no such thing as classes in JavaScript, but bear with me.