Interface interface, one of the JavaScript design patterns

高洛峰
Release: 2016-11-25 11:09:22
Original
1480 people have browsed it

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!