2011-04-17 52 views
19

如何省略隐藏我的变量从全局范围的自动封闭包装?摆脱CoffeeScript的封闭包装

(function() { 
    // my compiled code 
}).call(this); 

只是CoffeeScript的+ SproutCore的玩耍,当然,我宁愿离开这个范围,因为它是:在这种情况下,没有必要保护任何东西从覆盖。

我知道我可以在声明中使用@this.,但这不是太优雅。

+0

你应该_really_避免这样做。你不希望你的本地变量泄漏到全局范围中。 – shesek 2012-02-15 04:11:08

+5

@shesek也许他正在使用打包机?哪些已经将所有内容都包含在范围内?还是使用RequireJS?我认为包装范围应该是可选的。 – benqus 2013-09-07 15:31:18

+0

@benqus - 约定,我使用自己的包装器或将多个文件合并为一个大包装器,例如使用grunt。但除此之外,如果你觉得它很丑或什么的,你不应该忽略它。 – 2014-12-11 13:10:40

回答

42

快速和肮脏的解决方案:使用控制台标志-b(裸露)。 警告:如果你这样做,小猫会死!

干净的解决方案:不要这样做。

Usage: coffee [options] path/to/script.coffee 

    -c, --compile  compile to JavaScript and save as .js files 
    -i, --interactive run an interactive CoffeeScript REPL 
    -o, --output  set the directory for compiled JavaScript 
    -j, --join   concatenate the scripts before compiling 
    -w, --watch  watch scripts for changes, and recompile 
    -p, --print  print the compiled JavaScript to stdout 
    -l, --lint   pipe the compiled JavaScript through JSLint 
    -s, --stdio  listen for and compile scripts over stdio 
    -e, --eval   compile a string from the command line 
    -r, --require  require a library before executing your script 
    -b, --bare   compile without the top-level function wrapper 
    -t, --tokens  print the tokens that the lexer produces 
    -n, --nodes  print the parse tree that Jison produces 
     --nodejs  pass options through to the "node" binary 
    -v, --version  display CoffeeScript version 
    -h, --help   display this help message 
+11

这个答案是正确的,但值得注意的是'-b'几乎在所有情况下都不受欢迎。 [这是为什么](http://stackoverflow.com/questions/5211638/pattern-for-coffeescript-modules/5212449#5212449)。 – 2011-04-17 15:49:55

+0

谢谢!不知何故,我错过了... – Zeppelin 2011-04-17 15:57:59

+0

你会如何做到这一点从设置咖啡sinatra -b – coool 2012-01-20 20:38:19

7

我用另一个选项是我的全局变量附加到我的函数范围内的全局对象。我把我的附件放在'窗口'上。这会保持您的JavaScript封装并仅显示您在全局范围内需要的变量。

+0

在服务器上,使用'this'来代替。更好的是,两个都使用'@'。 – 2016-02-26 17:01:43