How to use object-oriented thinking to write JavaScript should be difficult for beginners. JQuery, which we often use, is actually encapsulated with object-oriented thinking, today, let's take a look at how to use interfaces in Javascript. in C # and JAVA, we should design our programs oriented to interfaces. in C # and Java, the keywords such as Interface are used, however, there is no corresponding mechanism in JavaScript, but Javascript is flexible. We can use its features to simulate the Interface, but we need to add some methods for the check action. Let's take a look at the role of the next Interface: After inheriting this Interface, you must implement the method (method signature) defined in this Interface. // JavaScript cannot implement the signature constraint of the method yet.
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 (arguments.length < 2) {
throw new Error("there is not Interface or the instance");
}
for (var i = 1; i < arguments.length; i++) {
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++) {
var method = interface1.Method[j];
if (!object[method] || typeof object[method] !== 'function') {
throw new Error("you instance doesn't implement the interface");
}
}
}
}
Let's analyze the code. Our current practice is to compare whether the method name in an Instance is defined in the interface. I first define an interface (two parameters), and the second parameter is the method name in the interface. The Check method uses a simple 2-layer for loop for comparison. Let's take a look at 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 comment out the above GetAge method, an error will occur during execution. This method was not implemented during ensureImplement. To be honest, this kind of layout is indeed very uglily. When you look at it, forgive me. If you haven't written it so much, you must write more in the future. By the way, I'm Alan_chen in MSDN forums for C # and DataPlatform (Entity Framework). If you need to forward, please indicate the source: http://www.cnblogs.com/jsjrjcj/archive/2011/05/25/2056627.html