Javascript Chainable Closure
Javascript Chainable Closure
受《如果海明威写Javascript》的启发,我想写一个带有私有局部变量的可链函数闭包。
预期的行为是:
> chainableCounter()
0
> chainableCounter(1)(2)()
3
下面是我的代码:
function chainableCounter(n) {
var acc = 0;
var fn = function (x) {
if (x === undefined) {
return acc;
} else {
acc = acc + x;
return fn;
}
};
fn(n);
}
当我尝试在节点REPL中运行这个时,我得到的是:
> chainableCounter()
undefined
> chainableCounter(1)
undefined
> chainableCounter(1)()
TypeError: undefined is not a function
chainableCounter(1)
返回undefined
而不是函数对象,这似乎表明我们永远不会到达return fn;
行。但更重要的是,为什么chainableCounter()
也返回undefined
当它应该返回0
?我错过了什么?
fn(n)
返回到调用点。你的实际函数chainableCounter
没有返回任何东西,它没有返回语句。
你可以在调用fn
之前添加它,像这样:
return fn(n);
应该是
return fn(n);
相关文章:
- Google Closure Advanced |无法识别对象属性|动态属性
- Angularjs$watch内部使用Closure
- 如何在高级编译模式下使用 Google Closure 编译器编译 jQuery UI 小部件
- RegExp的Google Closure编译器警告
- Javascript closure?
- Google Closure编译器为命名空间创建了不完整的别名
- @private注释在 Google Closure JavaScript 代码中实际上做了什么
- Google Closure Linter 在 Sublime Text 2 for Windows 中不起作用
- 如何使用 Google Closure API 移除调试代码
- closure-library在窗格之间拖动一个goog.fx.DragListGroup item
- Google Chrome Heap Snapshots (closure), (array), (system), (
- Javascript closure VS dojo lang.hitch
- Javascript Closure: Pratical Closures example in MDN
- Javascript Scope and Closure,变量保持其值
- Google Closure Compiler Service 提供无效代码
- Node.js vs Javascript Closure
- 使用 Google Closure Builder 时,我可以使用现有的 deps.js 文件而不是跟踪路径
- Javascript closure - mouse event
- AngularJS Google Closure Compiler with Google API
- Javascript Chainable Closure