Interface is an important concept in object oriented programming. It helps to reuse the code effectively.
So what is interface?
Interface provides a way to define what methods an object should have but not how it should be implemented. Interface allows to group objects based on what features they provide.
Javascript does not come with built-in support for interface. So in JavaScript it has to be manually ensure that a given class implements an interface.
Three ways to ensure interface in JavaScript:
- Comments,
- Attribute checking,
- Duck typing
/*
interface BasicMember {
function isMajor(age);
function isCitizen(ssn);
}
interface GoldMember {
function havingVisaCard(ccn);
}
*/
var RentACar = function(user, vehicle) { // implements BasicMember, GoldMember
// ...
}
// Implement the BasicMember interface
RentACar.prototype.isMajor = function(age) {
// ...
};
RentACar.prototype.isCitizen = function(ssn) {
// ...
};
// Implement the GoldMember interface
RentACar.prototype.havingVisaCard = function(ccn) {
// ...
};
This is just kind of documentation, Compliance is voluntary. Other two types will be explained in forth coming posts.