In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the function of the interface in javascript". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the role of the interface in javascript".
In javascript, an interface is a reference type that defines a contract, and an interface actually tells us which methods a class implements to help it use it; an interface makes the code more stable.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
There are no built-in methods to create or implement interfaces in JavaScript. Nor does it have built-in methods to determine whether one object implements the same set of methods as another. This makes it difficult to use objects interchangeably. But JavaScript is flexible, and we can do it in other ways.
What is an interface?
The interface actually defines which methods should be in the object. Instead of thinking about how these methods are implemented, he defines that the object has these methods.
An interface is a reference type that defines a contract. Other types implement interfaces to ensure that they support certain operations. Interface specifies the member that must be provided by the class or other interface that implements it. Like classes, interfaces can contain methods, properties, indexers, and events as members.
Benefits of Interfac
An interface actually tells us which methods a class implements. To help it use this class. Interfaces can make our code more stable if we add a method to the interface. If a class that implements it does not add this method accordingly, it will certainly throw an error.
Javascript Imitation Interface
There are three ways to emulate the JavaScript interface:
Annotation method
Attribute checking method
Duck variant method
Describe the interface with comments
Describing the interface with annotations is the easiest way, but the effect is the worst.
/ * interface Composite {function add (child); function remove (child); function getChild (index);} interface FormItem {function save ();} * / class CompositeForm {add (child) {/ /...} remove (child) {} getChild (index) {/ /...} save () {/ /...}
This imitation method is not very good, it does not check whether CompositeForm implements the method correctly, it is entirely through the programmers to consciously implement the interface in the comments. However, this implementation is very simple, but it is not helpful for testing and debugging.
Attribute checking imitating interface
This method is a little more cautious, but the interface is also written in the form of annotations, but you can see what interface a class claims to implement by examining a property.
Class CompositeForm {constructor () {this.implementsInterface = ['Composite',' FormItem'];}} function addForm (formInstance) {if (! implements (formInstance, 'Composite',' FormItem')) {throw new Error ('object does not implement interface method');} function implements (obj) {/ / this method query interface for (let I = 1; I)
< arguments.length; i++) { let interfaceName = arguments[i]; let interfaceFound = false; for (let j = 1; j < obj.implementsInterface.length; j++) { if (obj.implementsInterface[j] == interfaceName) { interfaceFound = true; break; } } if (!interfaceFound) { return false; } return true; }}addForm(new CompositeForm()); 这种方法的优点是他对类所实现的接口提供了文档说明,如果需要的接口不在我这个类宣称支持的接口之列(也就是说不在我的this.implementsInterface里),你就会看到错误信息。 缺点也显而易见,如果我的this.implementsInterface里宣称的和我注释里所定义的接口不一样但检查还是能通过的,就是调用addForm方法是不会爆破错的 用鸭式变型法模拟接口 其实,类是否声明自己支持哪些接口并不重要,只要具有这些接口中的方法就行。鸭式变型法把对象的方法集作为判断它是不是某个实例的唯一标准。实现原理也非常的简单:如果对象具有与接口定义的方法同名的方法,那么就可以认为他实现了这个接口。 // interfaceclass Interface { constructor(name, method) { if (arguments.length != 2) { throw new Error('两个参数:name method'); } this.name = name; this.method = []; for (let i in method) { if (typeof method[i] != 'string') { throw new Error('method 必须是字符串'); } this.method.push(method[i]); } } //检查接口方法 static ensureImplements(obj) { if (arguments.length < 2) { throw new Error('参数小于两个'); } for (let i = 1; i < arguments.length; i++) { var instanceInterface = arguments[i]; if (instanceInterface.constructor !== Interface) { throw new Error('你要检查的参数不属于Interface接口') } for (let j in instanceInterface.method) { let methodName = instanceInterface.method[j]; if (!obj[methodName] || typeof obj[methodName] !== 'function') { throw new Error(`请实现接口的${methodName}方法`) } } } }}// 实例化接口对象var Composite = new Interface('Composite', ['add', 'remove', 'getChild']);var FormItem = new Interface('FormItem', ['save']);// CompositeForm 类class CompositeForm { //... add() {} remove() {} getChild() {}}let c1 = new CompositeForm();Interface.ensureImplements(c1, Composite, FormItem);function addForm(formInterface) { ensureImplements(formInterface, Composite, FormItem);} 上面代码中的CompositeForm类中我没有实现save方法。运行这段代码就会报错。 但是鸭式变型法也是有缺点的,各个检查方面都是强制实施的。 本菜鸟实现方法 >I call myself the law of inheritance.
I use class inheritance to simulate the interface, see the code for implementation.
First, we define a class to use as an interface, and the property method represents the method set of the interface.
Class Interface {constructor () {this.mehods = ['add',' save', 'remove',' save'];} static ensureImplements (obj) {/ /...}}
Define a CompositeForm class that inherits this interface and calls the ensureImplements method detection interface of the parent class in the class
Class CompositeForm extends Interface {constructor () {super () .ensureImplements (this);}}
Perfect ensureImplements method
Class Interface {constructor () {this.mehods = ['add',' save', 'remove',' save'] } static ensureImplements (obj) {for (let i in this.mehods) {let methodName = this.mehods [I] if (! obj [methodName] | | typeof obj [methodName]! = 'function') {let err =' Please implement the method of API'+ methodName +'; throw new Error (err) Thank you for your reading. The above is the content of "what is the role of interfaces in javascript". After the study of this article, I believe you have a deeper understanding of what the role of interfaces in javascript is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.