In JavaScript, an interface is a declaration of a series of abstract methods and a collection of method characteristics. It provides a means of describing which methods an object should have. Interfaces can promote code reusability, help stabilize communication between different classes, and reduce problems that arise in the process of inheriting two objects.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
What is an interface
An interface is a declaration of a series of abstract methods and a collection of method characteristics. These methods should all be abstract. , needs to be implemented by a specific class, and then the third party can call this set of abstract methods to let the specific class execute specific methods.
Interfaces are one of the most useful tools in the object-oriented JavaScript programmer's toolbox. One of the principles of reusable object-oriented design proposed in design patterns 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 is no built-in method to create or implement an interface, and there is no set of methods that can determine whether an object implements the same as another object, which makes the relationship between objects It is difficult to use them interchangeably. Fortunately, JavaScript has excellent flexibility, which makes it easy to simulate traditional object-oriented interfaces and add these features.
The interface provides a means to specify which 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 can be used interchangeably in the A.I(B) method and B, as in B.I(A).
You can also use interfaces to develop commonality among 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 pros and cons of interfaces
The established interface is self-descriptive and can promote code reusability. The interface can provide a kind of information to tell an external class What 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.
In addition, any way of implementing an interface will have an impact on performance, partly due to the additional method call overhead. 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 of using 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 will be no check at runtime whether the interface follows the convention, but we can imitate it through auxiliary methods and explicit checks. most of its properties.
How to implement interfaces in JavaScript
There are three ways to implement interfaces in JavaScript:
(1) Comments describing the interface
(2) Attribute detection interface
(3) Duck type identification interface
Advantages: Easy to implement, no additional classes or functions required.
Disadvantages: Pure document constraints, the program cannot check whether the object that implements the interface implements all interface methods
/** * interface Composite{ * function a(); * function b(); * } */ // CompositeImpl implements Composite var CompositeImpl = function(){ //业务逻辑 }; CompositeImpl.prototype.a = function(){ //业务逻辑 }; CompositeImpl.prototype.b = function(){ //业务逻辑 };
The second method is more rigorous. All classes explicitly declare which interfaces they implement, and objects that want to interact with these classes can check these declarations. The interfaces themselves are still just annotations, but now you can tell what interface a class claims to implement by inspecting a property.
Advantages: Ability to check which interfaces are implemented
缺点:并未确保类真正实现了自称实现的接口。你只知道它是否说自己实现了接口。
var interfacesImpl = function(){ //在实现类内部用一个数组保存要实现的方法名 //通常这个属性名是团队中规定好的 //声明自己实现了这两个方法,但实际上并不一定 this.implementsInterfaces = ["Composite","FormItem"]; }; //专门为这个实现对象写一个检测函数,传入实例对象,用于检查实例对象是否实现了所有接口 function checkImplements(obj){ //调用检查方法 obj是否实现了两个接口,如果没有都实现则抛出异常 if(!isImplements(obj,"Composite","FormItem")){ throw new Error("接口没有全部实现!"); } //obj是要检查的对象 function isImplements(obj){ //传入的第0个参数是要检查的对象,所以从1开始检查 for(var i=1; i<arguments.length; i++){ //接收接口中每个接口的名字 var interfaceName = arguments[i]; //默认未实现该接口 var foundFlag = false; //循环查询传入实例对象的实现接口数组,检查是否全部实现 for(var j=0; j<obj.implementsInterfaces.length; j++){ //如果实现了这个接口,就修改标记并跳出 //debugger if(obj.implementsInterfaces[j] == interfaceName){ foundFlag = true; break; } } //如果遍历实现接口数组之后没找到,返回false if(!foundFlag){ return false; } } return true; } } //使用实例对象并检测 var o = new interfacesImpl(); checkImplements(o);
背后的观点:如果对象具有与接口定义的方法同名的所有方法,那么久可以认为它实现了这个接口。
/** * 接口类 * * @param {String} name 接口的名字 * @param {Array} methods 要实现方法名称的数组 */ var Interface = function (name, methods) { //判断参数个数 if(arguments.length !== 2){ throw new Error("接口构造器参数必须是两个!"); } this.name = name; this.methods = []; for(var i=0; i<methods.length; i++){ if(typeof methods[i] !== "string"){ throw new Error("接口实现的函数名称必须是字符串!"); } this.methods.push(methods[i]); } } //实例化接口对象---传入接口名和要实现的方法数组 var CompositeInterface = new Interface("CompositeInterface",["add","remove"]); var FormItemInterface = new Interface("FormItemInterface",["update","select"]); //实现接口的类 var CompositeImpl = function(){ } //实现接口的方法 CompositeImpl.prototype.add = function(obj){ //... } CompositeImpl.prototype.remove = function(obj){ //... } CompositeImpl.prototype.select = function(obj){ //... } //在这里少实现一个方法,下面检查是否全部实现了接口 // CompositeImpl.prototype.update = function(obj){ // //... // } //实例化 实现接口的对象 var c = new CompositeImpl(); //检验接口里的方法是否全部实现,如果不通过则抛出异常 Interface.ensureImplements = function(obj){ //如果接收到参数小于2,说明异常 if(arguments.length < 2){ throw new Error("接口检查方法的参数必须多余两个!"); } //接口实现检查 for(var i=0,len = arguments.length; i<len; i++){ //获取当前接口 var instanceInterface = arguments[i]; //判断接收到的是不是接口的对象,如果不是则抛出异常 if(instanceInterface.constructor !== Interface){ throw new Error("接口检测函数必须传入接口对象!"); } //检查实例化接口的对象是不是实现了接口里的所有方法 for(var j=0; j<instanceInterface.methods.length; j++){ //接收到的字符串方法 var methodName = instanceInterface.methods[j]; //如果obj里面没有methodsName这个方法,或者有这个属性但是不是函数,就抛出异常 if(!obj[methodName] || typeof obj[methodName] !== "function"){ throw new Error("接口方法" + methodName + "没有实现!"); } } } } //传入要检查的类,和要实现的所有接口对象 Interface.ensureImplements(c, CompositeInterface, FormItemInterface); c.add();
【相关推荐:javascript学习教程】
The above is the detailed content of What is an interface in javascript. For more information, please follow other related articles on the PHP Chinese website!