Home > Article > Web Front-end > A brief discussion on the detailed explanation of interface code in JavaScript
The interface is one of the most useful tools in the toolbox of the object-oriented JavaScriptprogrammer. One of the principles of reusable object-oriented design proposed in Design Pattern is "programming for interfaces rather than implementation programming", which is what we call interface-oriented programming. The importance of this concept is evident. But the problem is that in the world of JavaScript, there are no built-in methods for creating or implementing interfaces, and there is no set of methods that can determine whether an object implements the same as another object, which makes it difficult to use objects interchangeably. Fortunately, JavaScript has excellent flexibility, which makes it easy to simulate traditional object-oriented interfaces and add these features. An interface provides a means of describing what methods an object should have. Although it can indicate the meaning of these methods, it does not contain specific implementations. With this tool, objects can be grouped by the properties they provide. For example, if A and B and interface I, even if the A object and the B object are very different, as long as they both implement the I interface, then A and B can be used interchangeably in the A.I(B) method, such as B.I( A). You can also use interfaces to develop commonality between different classes. If a function that originally requires a specific class as a parameter is changed to a function that requires a specific interface as a parameter, then all objects that implement the interface can be passed to it as parameters. In this way, all objects that are not related to each other can be passed to it as parameters. Objects can also be treated the same.
The established interface is self-descriptive and can promote code reusability. The interface can provide a kind of information to tell the external class which methods need to be implemented. . It also helps stabilize the communication method between different classes and reduces problems that arise in the process of inheriting two objects. This is also helpful for debugging. In a weakly typed language like JavaScript, type mismatches are difficult to track. When using the interface, if a problem occurs, there will be a clearer error message. Of course, interfaces are not completely without shortcomings. Extensive use of interfaces will weaken their flexibility as a weakly typed language to a certain extent. On the other hand, JavaScript does not have built-in support for interfaces, but only simulates traditional object-oriented interfaces. This makes JavaScript, which is inherently flexible, more difficult to control. Additionally, any way you implement an interface will have a performance impact, due in part to the overhead of additional method calls. The biggest problem with using interfaces is that, unlike other strongly typed languages, JavaScript will fail to compile if it does not comply with the interface conventions. Its flexibility can effectively avoid the above problems. If it is in a collaborative development environment, Its interface is very likely to be damaged without causing any errors, which is uncontrollable.
In object-oriented languages, the way to use interfaces is generally similar. The information contained in the interface describes the methods that the class needs to implement and the signatures of these methods. Class definitions must explicitly state that they implement these interfaces, otherwise they will not compile. Obviously we can't do the same thing in JavaScript, because there are no interface and implement keywords, and there is no check at runtime whether the interface follows the contract, but we can imitate most of its features through auxiliary methods and explicit checks.
There are three main ways to imitate interfaces in JavaScript: through comments, attribute checking and duck-style debate. If the above three methods are effectively combined, it will Produce an interface-like effect.
Comments are a relatively intuitive way to put interface-related keywords (such as interface, implement, etc.) together with JavaScript code in comments to simulate the interface. This is the simplest method, but the worst effect. . The code is as follows:
//以注释的形式模仿描述接口 /* interface Composite{ function add(child); function remove(child); function getName(index); } interface FormItem{ function save(); } */ //以注释的形式模仿使用接口关键字 var CompositeForm =function(id , method,action) { //implements Composite , FormItem // do something } //模拟实现具体的接口方法 此处实现Composite接口 CompositeForm.prototype.Add=function(){ // do something } CompositeForm.prototype.remove=function(){ // do something } CompositeForm.prototype.getName=function(){ // do something } //模拟实现具体的接口方法 此处实现FormItem接口 Composite.prototype.save=function(){ // do something }
This method is actually not very good, because this kind of imitation only stays in the scope of document specifications. Whether developers will strictly abide by this agreement remains to be considered. Compliance with the interface completely depends on development. Consciousness of personnel. In addition, this method does not check whether a function actually implements the "interface" we agreed on. Nevertheless, this approach also has advantages. It is easy to implement without requiring additional classes or functions, and it can improve the reusability of the code because the interfaces implemented by the classes are annotated. This approach does not affect the space occupied by the file or the execution speed, because the commented code can be easily eliminated during deployment. But since no error message is provided, it doesn't help much for testing and debugging. The following method will check whether the interface is implemented. The code is as follows:
//以注释的形式模仿使用接口关键字 var CompositeForm =function(id , method,action) { //implements Composite , FormItem // do something this.implementsinterfaces=['Composite','FormItem']; //显式地把接口放在implementsinterfaces中 } //检查接口是否实现 function implements(Object){ for(var i=0 ;i< arguments.length;i++){ var interfaceName=arguments[i]; var interfaceFound=false; for(var j=0;j<Object.implementsinterfaces.length;j++){ if(Object.implementsinterfaces[j]==interfaceName){ interfaceFound=true; break; } } if(!interfaceFound){ return false; }else{ return true; } } } function AddForm(formInstance){ if(!implements(formInstance,'Composite','FormItem')){ throw new Error('Object does not implements required interface!'); } }
上述代码是在方式一的基础上进行完善,在这个例子中,CompositeForm宣称自己实现了Composite和FormItem这两个接口,其做法是把这两个接口的名称加入一个implementsinterfaces的数组。显式地声明自己支持什么接口。任何一个要求其参数属性为特定类型的函数都可以对这个属性进行检查,并在所需要的接口未在声明之中时抛出错误。这种方式相对于上一种方式,多了一个强制性的类型检查。但是这种方法的缺点在于它并未保证类真正地实现了自称实现的接口,只是知道它声明自己实现了这些接口。其实类是否声明自己支持哪些接口并不重要,只要它具有这些接口中的方法就行。鸭式辩型(像鸭子一样走路并且嘎嘎叫的就是鸭子)正是基于这样的认识,它把对象实现的方法集作为判断它是不是某个类的实例的唯一标准。这种技术在检查一个类是否实现了某个接口时也可以大显身手。这种方法的背后观点很简单:如果对象具有与接口定义的方法同名的所有方法,那么就可以认为它实现了这个接口。可以使用一个辅助函数来确保对象具有所有必需的方法,代码如下:
//interface var Composite =new Interface('Composite',['add','remove','getName']); var FormItem=new Interface('FormItem',['save']); //class var Composite=function(id,method,action){ } //Common Method function AddForm(formInstance){ ensureImplements(formInstance,Composite,FormItem); //如果该函数没有实现指定的接口,这个函数将会报错 }
与另外两种方式不同,这种方式无需注释,其余的各个方面都是可以强制实施的。EnsureImplements函数需要至少两个参数。第一个参数是想要检查的对象,其余的参数是被检查对象的接口。该函数检查器第一个参数代表的对象是否实现了那些接口所声明的方法,如果漏掉了任何一个,就会抛错,其中会包含被遗漏的方法的有效信息。这种方式不具备自我描述性,需要一个辅助类和辅助函数来帮助实现接口检查,而且它只关心方法名称,并不检查参数的名称、数目或类型。
在下面的代码中,对Interface类的所有方法的参数都进行了严格的控制,如果参数没有验证通过,那么就会抛出异常。加入这种检查的目的就是,如果在执行过程中没有抛出异常,那么就可以肯定接口得到了正确的声明和实现。
var Interface = function(name ,methods){ if(arguments.length!=2){ throw new Error('2 arguments required!'); } this.name=name; this.methods=[]; for(var i=0;len=methods.length;i<len;i++){ if(typeof(methods[i]!=='String')){ throw new Error('method name must be String!'); } this.methods.push(methods[i]); } } Interface.ensureImplements=function(object){ if(arguments.length<2){ throw new Error('2 arguments required at least!'); } for(var i=0;len=arguments.length;i<len;i++){ var interface=arguments[i]; if(interface.constructor!==Interface){ throw new Error('instance must be Interface!'); } for(var j=0;methodLength=interface.methods.length;j<methodLength;j++){ var method=interface.methods[j]; if(!object[method]||typeof(object[method])=='function')){ throw new Error('object does not implements method!'); } } } }
其实多数情况下,接口并不是经常被使用的,严格的类型检查并不总是明智的。但是在设计复杂的系统的时候,接口的作用就体现出来了,这看似降低了灵活性,却同时也降低了耦合性,提高了代码的重用性。这在大型系统中是比较有优势的。在下面的例子中,声明了一个displayRoute方法,要求其参数具有三个特定的方法,通过Interface对象和ensureImplements方法来保证这三个方法的实现,否则将会抛出错误。
//声明一个接口,描述该接口包含的方法 var DynamicMap=new Interface{'DynamicMap',['centerOnPoint','zoom','draw']}; //声明一个displayRoute方法 function displayRoute(mapInstance){ //检验该方法的map //检验该方法的mapInsstance是否实现了DynamicMap接口,如果未实现则会抛出 Interface.ensureImplements(mapInstance,DynamicMap); //如果实现了则正常执行 mapInstance.centerOnPoint(12,22); mapInstance.zoom(5); mapInstance.draw(); }
下面的例子会将一些数据以网页的形式展现出来,这个类的构造器以一个TestResult的实例作为参数。该类会对TestResult对象所包含的数据进行格式化(Format)后输出,代码如下:
var ResultFormatter=function(resultObject){ //对resultObject进行检查,保证是TestResult的实例 if(!(resultObject instanceof TestResult)){ throw new Error('arguments error!'); } this.resultObject=resultObject; } ResultFormatter.prototype.renderResult=function(){ var dateOfTest=this.resultObject.getData(); var resultArray=this.resultObject.getResults(); var resultContainer=document.createElement('p'); var resultHeader=document.createElement('h3'); resultHeader.innerHTML='Test Result from '+dateOfTest.toUTCString(); resultContainer.appendChild(resultHeader); var resultList=document.createElement('ul'); resultContainer.appendChild(resultList); for(var i=0;len=resultArray.length;i<len;i++){ var listItem=document.createElement('li'); listItem.innerHTML=resultArray[i]; resultList.appendChild('listItem'); } return resultContainer; }
该类的构造器会对参数进行检查,以确保其的确为TestResult的类的实例。如果参数达不到要求,构造器将会抛出一个错误。有了这样的保证,在编写renderResult方法的时候,就可以认定有getData和getResult两个方法。但是,构造函数中,只对参数的类型进行了检查,实际上这并不能保证所需要的方法都得到了实现。TestResult类会被修改,致使其失去这两个方法,但是构造器中的检查依旧会通过,只是renderResult方法不再有效。
此外,构造器中的这个检查施加了一些不必要的限制。它不允许使用其他的类的实例作为参数,否则会直接抛错,但是问题来了,如果有另一个类也包含并实现了getData和getResult方法,它本来可以被ResultFormatter使用,却因为这个限制而无用武之地。
解决问题的办法就是删除构造器中的校验,并使用接口代替。我们采用这个方案对代码进行优化:
//接口的声明 var resultSet =new Interface('ResultSet',['getData','getResult']); //修改后的方案 var ResultFormatter =function(resultObject){ Interface.ensureImplements(resultObject,resultSet); this.resultObject=resultObject; }
上述代码中,renderResult方法保持不变,而构造器却采用的ensureImplements方法,而不是typeof运算符。现在的这个构造器可以接受任何符合接口的类的实例了。
f35d6e602fd7d0f0edfa6f7d103c1b57工厂模式:对象工厂所创建的具体对象会因具体情况而不同。使用接口可以确保所创建的这些对象可以互换使用,也就是说对象工厂可以保证其生产出来的对象都实现了必需的方法;
2cc198a1d5eb0d3eb508d858c9f5cbdb组合模式:如果不使用接口就不可能使用这个模式,其中心思想是可以将对象群体与其组成对象同等对待。这是通过接口来做到的。如果不进行鸭式辩型或类型检查,那么组合模式就会失去大部分意义;
5bdf4c78156c7953567bb5a0aef2fc53Decorator pattern: Decorators work by transparently providing a wrapper for another object. This is achieved by implementing an interface that is exactly the same as that of the other object. To the outside world, there is no difference between a decorator and the object it wraps, so use an Interface to ensure that the created decorator implements the necessary methods;
23889872c2e8594e0f446a471a78ec4c Command mode: All command objects in the code implement the same batch of methods (such as run, ecxute, do, etc.). By using interfaces, classes created without executing these command objects do not need to know what these objects are, as long as Just know that they all implement the interface correctly. This allows you to create APIs with a high degree of modularity and low coupling.
The above is a brief discussion of the interface code in JavaScript. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!