Implement Interface in JavaScriptAn interface provide a way what the behavior of the object should have mean what the method of the object. But it does not say how those method and behavior should be implemented. This allow group of object have same behavior.
Advantage of using interface in Java ScriptEstablishment interfaces are self documenting and promote re usability. An interface tell programmer what method must be implement which make user to use and easier to find out error and unit test.
Disadvantage of using interfaced
Java Script is extremely expressive language. Using interface its behave some thing like strict typing. There is no built in support or keyword like interface so it is not easy to implements interface in Java Script. Every thing need to implements manually. Using interface implementation in Java Script will create a performance hot, due in the part of having another mehtod invocation.
In complex map application there are many implementation and every one ensure all have implement all method that need the application.
function displayRoute(mapInstance) {
Interface.ensureImplements(mapInstace, DynamicMap);
mapInstance.centerOnPoint(12, 34);
mapInstance.zoom(5);
mapInstance.draw();
...
}
If any one want to use the display Route function then he/her must implement all the method like centerOnPoint, zoom and draw
Step by Step Interface implementation:
Simple Student class,
In Java:
interface IStudent{
void setName(String name)
String getName();
}
public class Student implements IStudent{
private String name
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
In Java Script
1. Create Interface function that store the name of the implementation and name of the method.
var Interface = function(name, methods) {
if(arguments.length != 2) {
// alert("Expected two argument..");
throw new Error("Interface constructor called with " + arguments.length
+ "arguments, but expected exactly 2.");
}
this.name = name;
this.methods = []; //store the mehod name
for(var i = 0, len = methods.length; i <>
2. Create the static method of the Interface ensure the implementation.
Interface.ensureImplements = function(object) {
if(arguments.length < i =" 1," len =" arguments.length;" interface_ =" arguments[i];" j =" 0," methodslen =" interface_.methods.length;" method =" interface_.methods[j];">
3. Create Interface variable
var IStudent = new Interface('Student1',['setName','getName']);
var Student = function(){ };
Student.prototype.setName = function(name){
this.name = name;
}
Student.prototype.getName = function(){
return this.name;
}
function studentOperation(student){
Interface.ensureImplements(student, IStudent);
student.setName('Test Student1');
alert(student.getName());
}
5. Use the interface
function studentOperation(student){
Interface.ensureImplements(student, IStudent); // Must check the
student.setName('Test Student1');
alert(student.getName());
}