官术网_书友最值得收藏!

  • MooTools 1.3 Cookbook
  • Jay Larry G. Johnston
  • 354字
  • 2021-04-02 19:07:07

Understanding MooTools ubiquitous anonymous functions

Functions have names, but anonymous functions do not; MooTools uses them everywhere.

Note

Anonymous functions are one-time use like disposable lighters. In MooTools, we use them to one-time define a method; reusable disposable functions!

Getting ready

To define and call an anonymous function raw JavaScript wraps a function in parentheses:

(function(){document.title=location.href;alert('done');})();

Nothing is returned, and the function is not assigned to a function identifier; when the () function syntax is appended, the function self-executes.

How to do it...

MooTools' use differs slightly in that we will pass this anonymous function as an argument to a MooTool object and bind it to an identifier; the anonymous syntax does not change.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<div id="my_trigger" style="width:100px; height:100px; border:1px solid #BEBEBE; line-height:50px; text-align:center;">Click Me</div>
<script type="text/javascript">
// (A) would change title, alerts done in true lisp style
//(function(){document.title=location.href;alert('done');})();
// (B) saves the anonymous function in a variable
var af = (function(){
document.title=location.href;
alert('done');
});
// (C) "calls" the anonymous function (commented out)
//af();
// (D) returns the function (and alerts its text)
//alert($lambda(af)); // note, lambda is deprecated
// (E) binds function to the click event on my_trigger
$('my_trigger').addEvent('click',
af
);
</script>

How it works...

  • A indicates a classical JavaScript style, anonymous, self-executing function.
  • B (used in our recipe) assigns a self-executing function to an identifier.
  • C in raw JavaScript would call the self-executing function.
  • D demonstrates deprecated usage of MooTools' $lambda object.
  • E (used in our recipe) passes the function to be bound to click events.

There's more...

Speaking in a strictly semantic world where anonymity is not compromised by that golden oldie 1984 and Orson Wells' cameras and dictatorial fiction, an anonymous function cannot be called more than once; it is defined, executed, and lost. Assigning it to an identifier would, in a pure discourse, render it no longer anonymous. Verily, the point of a recipe on anonymous functions is but to aid us in our understanding behind the science on how functions are passed to objects and then later executed as methods. Read up on more about what anonymous functions are on your favorite wiki site and send the author assertively argumentative proof as to the gamut of viewpoints regarding this subject.

主站蜘蛛池模板: 衡水市| 桂平市| 柳江县| 罗定市| 沅江市| 方正县| 扶绥县| 陆河县| 突泉县| 丹寨县| 海门市| 勐海县| 启东市| 陕西省| 交城县| 长宁县| 河曲县| 吉首市| 贞丰县| 辽阳县| 龙口市| 定陶县| 美姑县| 黄大仙区| 安阳市| 西安市| 巴青县| 太和县| 泗水县| 邹城市| 辰溪县| 辉县市| 望奎县| 石台县| 青冈县| 焉耆| 六安市| 吉安市| 拜泉县| 洛川县| 丹棱县|