How to use object-oriented thinking to write JavaScript should be difficult for beginners. The JQuery we often use is actually encapsulated with object-oriented thinking. Today we will take a look at how to use Interface in Javascript and C# In JAVA, our programs should be designed for interfaces. There are keywords like Interface in C# and Java, but there is no corresponding mechanism in JavaScript. However, Javascript is very flexible. We can use its characteristics to imitate Interface, but we need Add some methods to do the checking action.
Let’s take a look at the role of the next Interface:
If you inherit this Interface, you must implement the method (method signature) defined in this Interface
//JavaScript cannot currently implement the constraints of method signatures
var Interface = function (name, methods) {
if (arguments.length != 2) {
throw new Error("the interface length is bigger than 2");
} this.Name = name; this. Method = [];
for (var i = 0; i < methods.length; i++) {
if(typeof methods[i]!== string) {
throw new Error("the method name is not string"); this.Method.push(methods[i]);
}
/*static method in interface*/
Interface.ensureImplement = function (object) {
if { var interface1 = arguments[i]; If (interface1.constructor !== Interface) {
throw new Error("the argument is not interface");
}
for (var j = 0; j < ; interface1.Method.length; j++) {throw new Error( "you instance doesn't implement the interface"); Whether the method name in an Instance is defined in the interface.
I first define an interface (2 parameters), and the second parameter is the method name in the interface. The Check method uses a simple 2-level for loop to perform comparison actions.Let’s see how to use this interface:
var Person = new Interface("Person", ["GetName", "GetAge"]); var Man = function (name, age) { this.Name = name; this .Age = age; } Man.prototype = { GetName: function () { return this.Name; }, // GetAge: function () { return this.Age; } } var test = function (instance) { Interface.ensureImplement (instance, Person); var name = instance.GetName(); alert(name); } test(new Man("Alan",20));If we annotate the above GetAge method, it will be executed during execution Something went wrong. When ensuringImplement, I found that this method was not implemented.