Home >Web Front-end >JS Tutorial >JavaScript DSL fluent interface (using chain call) example_javascript skills

JavaScript DSL fluent interface (using chain call) example_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:09:241493browse

After studying DSL carefully for a while, I discovered several interesting things. One of the most used things in JavaScript is probably chained calls (Method Chaining). Interestingly, Martin Flower pointed out:

Copy code The code is as follows:

I've also noticed a common misconception - many people seem to equate fluent interfaces with Method Chaining. Certainly chaining is a common technique to use with fluent interfaces, but true fluency is much more than that.

Many people equate chained calls with fluent interfaces. However, chain call is a common method of fluent interface, and the real fluent interface is more than that.

DSL smooth interface

The original intention of fluent interface is to build a readable API. After all, the code is written for people to read.

Similarly, let’s take a brief look at how we manipulated the DOM through method cascading earlier

Copy code The code is as follows:

var btn = document.createElement("BUTTON"); // Create a
If written with jQuery, it looks like this

Copy code The code is as follows:
$('').append("CLICK ME");

Wait
So we can create a simple example to show this simplest DSL


Copy code The code is as follows:
Func = (function() {
This.add = function(){
console.log('1');
         return this;
};
This.result = function(){
console.log('2');
         return this;
};
Return this;
});
var func = new Func();

func.add().result();

However this looks like an expression generator.

DSL expression generator

The expression generator object provides a set of coherent interfaces, and then converts the coherent interface calls into calls to the underlying command-query API.

Such an API can be seen in some APIs about databases:


Copy code The code is as follows:
var query =
SQL('select name, desc from widgets')
.WHERE('price < ', $(params.max_price), AND,
            'clearance = ', $(params.clearance))
.ORDERBY('name asc');

One problem with chained calls is the ending. In the code above, we don’t have the ending, which is very confusing. . Adding a query and end seems to be a good result.

Others

Method cascade

Expressed as follows:

Copy code The code is as follows:
a.b();
a.c();

Statement:
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