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!");
输出:
function: Foo
A RegExp: /bar/
A string: baz!
Is plain JavaScript, it is a function chaining pattern.
The first line, ( fab = require("fab") ) includes the fab function and returns a reference to it.
All the subsequent parentheses are function calls, each function invocation returns probably the same function again and again.
The pattern probably looks like this simplified example:
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!");
发布评论
评论(2)
是纯 JavaScript,它是一个函数链模式。
第一行
( fab = require("fab") )
包含fab
函数并返回对其的引用。所有后续的括号都是函数调用,每个函数调用可能一次又一次返回相同的函数。
该模式可能类似于这个简化的示例:
输出:
Is plain JavaScript, it is a function chaining pattern.
The first line,
( fab = require("fab") )
includes thefab
function and returns a reference to it.All the subsequent parentheses are function calls, each function invocation returns probably the same function again and again.
The pattern probably looks like this simplified example:
Outputs:
这确实很难理解;它看起来根本不像Javascript...
无论如何,FAB 利用返回一个指向被调用函数的指针。例如:
当然,您可以实现额外的条件,例如计算参数数量或检查传入参数的类型。例如:
最后一个示例警报:
That's hard to follow indeed; it doesn't really look like Javascript at all...
Anyway, FAB takes advantage of returning a pointer to the function which was called. For example:
Of course you can implement extra conditions, like counting the number of arguments or checking the type of arguments passed in. For example:
The last example alerts: