Ways to give JavaScript the ability to program like lambda expressions _javascript tips

Source: Internet
Author: User
Tags closure function definition
But I also told People later, because there are too many parameters to accept, so if you don't write smart tips very clearly, even I often do not know how to use.

However, the acceptance of many parameters, in addition to the easy to mistake usage, there will be another problem, this is what I write out today the reason for this issue.
Look at the JS version of the page number rendering component of the full version of the function signature:
Copy Code code as follows:

function Pnview (
CurrentPage, Actioncurrent,
Beginpage, EndPage,
Actionbegin, Actionend,
Currentsiblings, Actioncurrentsibling,
Preventfolding, Actionfolding,
Endofbegin, Beginofend,
Actionbeginsibling, actionendsibling
)

As you can see, this fully customizable full function signature accepts 14 parameters, and half of them-that is, 7 parameters-Accept the callback function.
The problem is that you need to write a combination of characters such as "function () {}" more than once, like this:
Copy Code code as follows:

function ww (s) {document.write (s);}
function ws (n) {ww (' <a href= ' # ' > (' + n + ') </A> ');
Pnview (. function (n) {ww (' [' + n + '] ')},
1, 27,
function (n) {ww (' <a href= "#" >|< ' + n + ' </A> ');}, function (n) {ww (' <a href= "#" > ' + N + ' > |</a> '); },
2, WS,
1, function () {ww (' ..... '); },
2, 2,
WS, WS
);

When I test this component in a Web page, I feel like I miss the lambda expression in C #-although some people, some JS frameworks call anonymous functions "lambda expressions", but that's just the equivalent of "Anonymous delegates/Functions" in C #. The (surface) character of a lambda is to use a short syntax pattern to reflect the logic of a (callback) function/process (or action) without being distracted by "delegate" or any other keyword.

For this reason, I've written a module that translates JS code and translates a particular pattern into a function definition.
After using this module, the preceding call can look like this:
Copy Code code as follows:

Eval (function () {
var ww = (S, document.write (s));
var ws = (n, ww (' <a href= "#" > (' + n + ') </A> ');
Pnview (N, ww (' [' + n + '] '),
1, 27,
(N, WW (' <a href= "#" >|< ' + n + ' </A> ')), (N, ww (' <a href= "#" > ' + n + ' >|</A> ')),
2, WS,
1, (0, ww (' ...) ')),
2, 2,
WS, WS
);
}.lamda ()) ();

The complete code for the module is as follows:
Copy Code code as follows:

/*!
L-amda "A-lambda", a module provides alternate "LAMBDA" style programming ability for JavaScript.
Created by Nanalich. 2010-09-08
This module is published under WTFPL v2 and so you just do WHAT the Fxxx to and it.
*/
!function () {
function Attachentry (o, A, m) {
var i, J, N;
o = [].concat (o);
if (!) ( o instanceof Array)) o = [O];
while (i = O.shift ()) {
For (J in a) {
if (!i[n = A[j]]) i[n] = m;
}
}
}
var rx0 =/^\s* (0| Nan|null) \s*,$/;
var rx1 =/([\w]\s*) \ (\s*0\s*,| (?: \ s*[a-z_$][\w$]*\s*,) +) | " (\\[\s\s]| [^\x22]) *"|' (\\[\s\s]| [^\x27]) * '/gi;
var rx2 =/\)/g;
function Rxgetflags (RX) {//Remove the creation option for a regular expression
Return (Rx.global?) ' G ': ' + (rx.ignorecase? ' I ': ' + (rx.multiline? ' m ': ');
Return/\/([gim]*) $/.exec (' + Rx ') [1];
}
Attachentry (REGEXP, [' GetFlags '], rxgetflags);
Attachentry (Regexp.prototype, [' getflags '], function () {
Return Rxgetflags (this);
});

function Translatelambda (s) {
if (typeof (s)!= ' string ') s = ' + S;
var x = new RegExp (Rx1.source, Rx1.getflags ());
var y = new RegExp (Rx2.source, Rx2.getflags ()); Because browsers such as Firefox and Safari are overly optimized for global matching regular expressions, there is a roundabout way to create an instance of a regular expression that is not repeated.
var m, l = 0, r = ';
while (M = x.exec (s)) {
var C = m[0], h, p, Q, t;
Switch (C.charat (0)) {//Judge expected grammatical composition
Case ' $ ':
Case ') ':
Case '] ':
Case ' "':
Case "'":
Continue function arguments, skipping
}

h = m[2];
if (Rx0.test (h))
h = ';
Else
h = h.substr (0, h.length-1); Remove the comma at the end
R + = s.substring (l, p = m.index); Append the remaining content to the result string
Y.lastindex = L = p + c.length; Start looking for closing parenthesis after comma
while (q = y.exec (s)) {
Q = q.index;
try {
t = ' return ' + s.substring (l, Q) + '; ';
New Function (t); Grammar test
R + + C + ' function (' + H + ') {' + TRANSLATELAMBDA (t) + '} '; The contents of the translation
R + + m[1] + ' function (' + H + ') {' + TRANSLATELAMBDA (t) + '} '; The contents of the translation
X.lastindex = L = q + 1; The next lookup starts after the parentheses
Break
catch (ex) {}
}
if (!q) L = p; Note You cannot find a closing parenthesis or a valid code to append all the matching content directly
}
try {
R + + S.SUBSTR (l);
if (/[\w$]*| " (\\[\s\s]| [^\x22]) *"|' (\\[\s\s]| [^\x27]) * '/.exec (R) [0] = = ' function ')//rough judgment of whether or not functions (can handle most situations)
r = ' 0, ' + R; Use this "weird" form to get the expected results in all browsers, including IE
New Function (R); Grammar test
return R;
catch (ex) {//failed, return original
return s;
}
};

var lamdaaliases = ["Translatelambda", "Lambda", "Lamda"];
Attachentry ([Function, String], lamdaaliases, TRANSLATELAMBDA);
Attachentry ([Function.prototype, String.prototype], lamdaaliases, Function () {
Return Translatelambda (this);
});
} ();

If compared to the lambda expressions in C #, my module still has a lot of drawbacks, but now I'm satisfied with this, at least I don't have to write too many "function".
In short, the specification of this module is like this--
Advantages:
Reduce the number of "function" occurrences when writing code;
Using syntax patterns (pattern), which can be edited normally in the normal JavaScript editor, does not cause syntax errors when written directly in the function body.
Limitations:
Use of this module at any time must invoke the translation method ("Translatelambda", "lambda" or "Lamda") and the Eval function, which cannot be omitted;
If a function A is present, it is not possible to interpret a to pass the argument passed to a (that is, A.LAMBDA () or a similar operation does not make a ((x, X, 2) equal to a (function (x) {return x * 2;}). );
Cannot contain any statement other than an expression and cannot contain the use of ";" To separate multiple statements.
Disadvantages:
Consecutive parentheses may make the code difficult to understand;
No editor can provide syntax highlighting for lambda expressions;
There is the possibility of incorrectly translating existing code-the module chooses to match the pattern in which there is no practical value in the normal code, patterns that do not normally appear, such as: (x, X * 2) are equivalent to pure X * 2, (0, A.method ()) equivalent to Pure A.method (), So the probability of this disadvantage affecting the actual code is nearly 0.
Here are some of the improper uses:
1, the use of this module does not save a lot of code when: putting the cart before the horse.
Copy Code code as follows:

Eval (function () {///not only does not reduce the amount of code, but also increases the
Window.onload = (0, alert (' Load complete! '));
}.lambda ());

2. Translation of functions that accept parameters: this has been mentioned before.
Copy Code code as follows:

Eval (Somefunction.lambda ()) ((X, X.tostring (16)); Somefunction may produce unexpected results, and the received arguments will be the result of x.tostring (16) (if x is not defined here, a "variable does not exist" exception), not a callback function.

3, in order to use this module and circumvent the grammar check:
Because of the use of grammar that is valid but not practical in JavaScript, it is not necessary to circumvent grammar checking.
Copy Code code as follows:

Eval ("somefunction (x, X.tostring)". LAMDA ()); Without a grammar check, you may have an accident at run time

4, in (pseudo) lambda use too many operations, or even more than one statement:
In designing this module, I did not find patterns (pattern) that could be used with multiple statements and could be checked by syntax, because the amount of code added by "function", "return" and so on in a lambda expression is usually negligible. Using lambda expressions in this way is inherently a departure from the original idea.
Copy Code code as follows:

Eval (function () {somefunction (x, y.something (x); return x.tostring (16)); Lamda ()) (); Syntax error
Eval (function () {somefunction (x, y.something (x), x.tostring (16)); Lamda ()) (); Easy to produce ambiguity in understanding
Eval (function () {somefunction ((x, ++x)); Lamda ()) (); Simple expressions can be accepted.

Best Use occasion:
Now many people writing JavaScript like to write their own code in a closure, so as to avoid global scope pollution problems, like this:
Copy Code code as follows:

(function () {
All the code is in here.
})();

This "big" closure is just the best place to use this module:
Copy Code code as follows:

Eval (function () {//parentheses add eval before
All the code is in here.
}.lamda ()) (); Add in parentheses. LAMDA ()

Yesterday CodePlex, code and release upload error. Consider the use of this module is limited, not suitable for those who lack JavaScript experience to use, so do not provide additional source code package download-If necessary, please copy directly from the text.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.