CoffeeScript惰性函数的实现
我想在 JavaScript
var init = function () {
// do some stuff once
var once = true
// overwrite the function
init = function () {
console.log(once)
}
}
CoffeeScript 中添加另一个本地 var init 到初始 init 中,这样第二个 init 就不会覆盖第一个 init
var init = function () {
var init //automatically declared by coffeescript
// do some stuff once
var once = true
// overwrite the function
init = function () {
console.log(once)
}
}
。对于解决方案/解决方法的一些提示,我们将不胜感激。
I would like to something like this in JavaScript
var init = function () {
// do some stuff once
var once = true
// overwrite the function
init = function () {
console.log(once)
}
}
CoffeeScript adds another local var init to the initial init so the second init doesn't overwrite the first one
var init = function () {
var init //automatically declared by coffeescript
// do some stuff once
var once = true
// overwrite the function
init = function () {
console.log(once)
}
}
Some tips for solutions / workarounds would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(更新:下面的答案当时在 CoffeeScript 1.0.1 下是准确的。在 CoffeeScript 1.1.0 下不再是这种情况,解决了这个问题。)
哇,这让我感到惊讶。 CoffeeScript
声明了外部
init
和内部init
。在我看来,这更可能是一个错误,而不是有意识的语言设计决策——编译器在评估外部init =
赋值之前更简单地评估函数。我已经对此提出了问题。这是一种解决方法:
现在只有一个
init
,即具有最外层作用域的那个。(Update: The answer below was accurate at the time, under CoffeeScript 1.0.1. It is no longer the case under CoffeeScript 1.1.0, which fixed this issue.)
Wow, this surprises me. The CoffeeScript
declares both an outer
init
and an innerinit
. This strikes me as more likely a bug than a conscious language design decision—the compiler simpler evaluates the function before it evaluates the outerinit =
assignment. I've gone ahead and filed an issue on this.Here's a workaround:
Now there's only one
init
, the one with the outermost scope.我相信这是设计使然。您不应该依赖隐式全局变量。
init
是 window/global 对象的属性,因此只需正确引用它即可:I believe this is by design. You shouldn't rely on implicit globals.
init
is a property of the window/global object, so just reference it correctly: