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
1. Comment description interface: Not recommended
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(){ //业务逻辑 };
2. Attribute detection interface: not recommended
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);
3、鸭式辨型法:推荐
背后的观点:如果对象具有与接口定义的方法同名的所有方法,那么久可以认为它实现了这个接口。
/** * 接口类 * * @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!

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version