nev*_*ame 19 javascript chaining node.js floating-action-button
我看过一张幻灯片,它提供了一个node.js框架Fab.

这是JavaScript吗?
有人可以解释一下代码中发生了什么吗?
我都输了.
CMS*_*CMS 22
是纯JavaScript,它是一个函数链模式.
第一行( fab = require("fab") )包括fab函数并返回对它的引用.
所有后续括号都是函数调用,每个函数调用可能会一次又一次地返回相同的函数.
该模式可能看起来像这个简化的例子:
var foo = function (arg) {
// detect what the argument is
if (typeof arg == 'function') {
// do something with arg
console.log('function: '+arg());
} else if (arg instanceof RegExp) {
// arg is a RegExp...
console.log('A RegExp: '+arg);
} else if (typeof arg == "string") {
// arg is a string
console.log('A string: '+arg);
}
return foo; // return a reference to itself
};
(foo)
(function() { return "Foo "; })
(/bar/)
(" baz!");
Run Code Online (Sandbox Code Playgroud)
输出:
function: Foo A RegExp: /bar/ A string: baz!
这确实难以理解; 它根本不像Javascript ......
无论如何,FAB利用返回指向被调用函数的指针.例如:
function doSomething(str){
alert(str);
return arguments.callee;
}
// Alerts 'hi' and then 'there'
doSomething('hi')('there');
Run Code Online (Sandbox Code Playgroud)
当然,您可以实现额外的条件,例如计算参数的数量或检查传入的参数的类型.例如:
function doSomething(){
if(arguments.length == 1){
alert(arguments[0])
}
else if(arguments.length == 2){
alert(arguments[0] + arguments[1]);
}
return arguments.callee;
}
doSomething
("Hi, 3 + 4 is:")
(3, 4);
Run Code Online (Sandbox Code Playgroud)
最后一个示例提醒:
> Hi, 3 + 4 is:
> 7
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3510 次 |
| 最近记录: |