Skip to content

Instantly share code, notes, and snippets.

@EnotionZ
Created May 8, 2010 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EnotionZ/394702 to your computer and use it in GitHub Desktop.
Save EnotionZ/394702 to your computer and use it in GitHub Desktop.
An implementation of the interface system in Javascript that takes a design form similar to other popular object-oriented languages such as Java, C# and PHP.
/* An implementation of the interface system in Javascript that takes a design form
similar to other popular object-oriented languages such as Java, C# and PHP. */
Function.prototype.implements = function(){
var class = this;
if(arguments.length < 1) {
throw new Error("Expecting interface as argument but found none.");
}
for (var i =0; i<arguments.length; i++){
var interface = arguments[i], interfaceType = typeof interface;
var foundInterface = false;
if(interfaceType !== 'object') {
throw new Error("Expecting interface type 'object' but found '" + interfaceType + "'");
}
for(var method in interface) {
var foundMethod = false;
for(var definedMethod in class) {
if (definedMethod === method){
foundMethod = true;
break;
}
}
if (!foundMethod){
for(var definedMethod in class.prototype) {
if (definedMethod === method){
foundMethod = true; /* found the method within the class prototype */
break;
}
}
}
if (!foundMethod) {
throw new Error("Expecting interface method '" + method + "'");
}
}
}
}
/* Interface Declaration */
var interfacePerson = {
getName: function(){},
getAge: function(){}
}
var interfaceEmployee = {
getSalary: function(){}
}
/* Class declaration */
var Developer = function(opts){
var salary = typeof opts !== 'undefined' && typeof opts.salary !== 'undefined' ? opts.salary : 0;
this.getSalary = function(){
return salary
}
}
Developer.prototype = {
getName: function(){
return this.name;
},
getAge: function(){
return this.age;
}
}
/* throws no argument error */
//Developer.implements();
/* throws type error */
//Developer.implements('String');
/* throws 'interface not found' error */
//Developer.implements(['getName','getAge']);
/* this will fail because getSalary is not defined in the prototype object of Developer */
//Developer.implements(interfacePerson,interfaceEmployee);
/* this will pass. The methods in Developer implements the interface interfacePerson */
Developer.implements(interfacePerson);
var enotionz = new Developer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment