开发者

CoffeeScript lazy function implementation

开发者 https://www.devze.com 2023-02-15 17:48 出处:网络
I would like to something like this in JavaScript var init = function () { // do some stuff once var once = true

I would like to something like this in JavaScript

var init = function () {
              // do some stuff once
              var once = true

              // o开发者_JS百科verwrite 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.


(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

init = ->
  init = -> console.log once

declares both an outer init and an inner init. This strikes me as more likely a bug than a conscious language design decision—the compiler simpler evaluates the function before it evaluates the outer init = assignment. I've gone ahead and filed an issue on this.

Here's a workaround:

init = null
init = ->
  init = -> console.log once

Now there's only one init, the one with the outermost scope.


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:

window.init = ->
    var once = true
    window.init = ->
        console.log once
0

精彩评论

暂无评论...
验证码 换一张
取 消