After carefully studying DSL for a while, I found several interesting things. The thing that JavaScript uses most is probably chain calls (method chains, namely Method Chaining). Interestingly, Martin Flower pointed out:
The code copy is as follows:
I've also noticed a common misconception - many people seem to equal 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 chain calls with smooth interfaces. However, chain calls are a common method for smooth interfaces, and there are more than just a little bit of real smooth interfaces.
DSL smooth interface
The original intention of a smooth interface is to build a readable API, after all, the code is written for people to see.
Similarly, let's take a look at the DOM earlier, we used method cascade to operate
The code copy is as follows:
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode("CLICK ME"); // Create a text node
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn); // Append <button> to <body>
And if you write in jQuery, that's it
The code copy is as follows:
$('<span>').append("CLICK ME");
etc.
So we can create a simple example to show the simplest DSL
The code copy 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 that are then converted into calls to the underlying command-query API.
Such an API, we can see in some APIs about databases:
The code copy is as follows:
var query =
SQL('select name, desc from widgets')
.WHERE('price < ', $(params.max_price), AND,
'clearance = ', $(params.clearance))
.ORDERBY('name asc');
There is a problem with chain calls that end. We did not end in the same code as above, which is very confusing. . Adding a query and end seems to be a good result.
other
Method cascade
It is expressed as follows:
The code copy is as follows:
ab();
ac();