Skip to content

Late interface binding

ALexeyP0708 edited this page Jul 5, 2020 · 1 revision

This method is necessary when the class was formed earlier and it is necessary to implement a new class in the likeness of an existing one in accordance with the rules of the interface. It may be convenient to use it when refactoring or creating a class based on existing methods.

class MyClass {
	myMethod(){
		return 'Hello';
	}
}
class MyClass2 extends MyClass {
	myMethod2(){
		return 'bay';
	}
}

class MyInterface  { 
	myMethod(){}
	myMethod2(){
		return {
			arguments:[],
			return:{
				types:'string'
			}
		}
	}
	myMethod3(){
			return {
			arguments:[],
			return:{
				types:'string'
			}
		}
	}
}
MyInterface.isInterface=true;
class MyClass3 extends MyClass2 {
}
try{
	// late binding of the interface to the class.
	// will throw an error since myMethod3 is not implemented.
	InterfaceManager.implementInterfaces(MyClass3,MyInterface);
}catch(e){
	console.error(e);
}
class MyClass4 extends MyClass2  {
	myMethod3(){
		return 'Word';
	}
}
// late binding of the interface to the class.
/* successfully validate for the presence of methods myMethod, myMethod2, myMethod3 */
InterfaceManager.implementInterfaces(MyClass4, MyInterface); 
let myObj=new MyClass4 ();

/* since it is declared before interface,
 it does not check for passing arguments and for the return value */
myObj.myMethod();

/* since it is declared before interface, 
it does not check for passing arguments and for the return value */
myObj.myMethod2(); 

/* since it is declared after interface, 
it checks for passing arguments and for the return value.*/
myObj.myMethod3(); 

class MyClass5  {
	myMethod3(){
		return 'Word';
	}
}

/* successfully check for the presence of methods myMethod,myMethod2,myMethod3 */
InterfaceManager.implementInterfaces( MyClass5,false,true, MyInterface); 

let myObj2=new MyClass5 ();

/* since it is declared after interface,  
it checks for passing arguments and for the return value. 
(see 3 argument in implementInterfaces ) */
myObj2.myMethod(); 

/* since it is declared after interface,  
it checks for passing arguments and for the return value. 
(see 3 argument in implementInterfaces ) */
myObj2.myMethod2();

/* since it is declared after interface, 
it checks for passing arguments and for the return value.*/
myObj2.myMethod3();