Created
May 8, 2010 18:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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