Best Practices for "Abstract" functions in JavaScript?
Just don't define the function.
Javascript is a duck-typed language. If it looks like a duck and it quacks like a duck, it is a duck.
You don't need to do anything special to make this work; as long as the function exists when you call it, it will work fine.
If you call it on an instance that doesn't have the function, you'll get an error at the callsite.
As our team is growing and our javascript project is getting more complex we have to start implementing OO features as well.
In our javascript 'abstract' method we simply throw an error, or pop up an alert. This is an example from out Page object:
Page.initialLoad = function() { //abstract
alert('Page.initialLoad not implemented');
};
In java world it is analagous to :
public void abstract initialLoad();
The Java code gives a compile time error, however in the Javascript we would get a runtime error. (a dirty error dialog saying that an implementing object hasn't implemented that method yet).
We have a number of disparate teams that use the Page object; the philosophy of 'duck typing' absolutely does not cut it with us. Without these pseudo 'abstract' methods we have a general lack of API communication, and sometimes we get sabotaging of the super object (ie. because a user has no idea they are supposed to implement the method).
I am tired of this 'duck typing' philosophy. I'm not sure if proponents have ever been in a complex Javascript project with 10+ developers.
I agree with SLaks, there's no need to define the function, but I tend to anyway. That's because to me the important part is in the documentation. When somebody reads my class, I want it to be clear that you must implement these methods, what arguments will be passed and what should be returned.
This is from a file at work. There were multiple implementations of a feature with a base class that did the data loading at intervals.
/**
* Called when data is received and should update the data buffer
* for each of the charts
*
* @abstract
* @param {cci.ads.Wave[]} waves
* @void
*/
updateChartsData: function(waves){
throw "Abstract method updateChartsData not implemented";
},
2019 Update
Use TypeScript if you can Declaring abstract method in TypeScript