Coffeescript“命名空间”中的类
我在 Coffeescript FAQ 上找到了这个用于创建简单命名空间的代码片段。
# Code:
#
namespace = (target, name, block) ->
[target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3
top = target
target = target[item] or= {} for item in name.split '.'
block target, top
# Usage:
#
namespace 'Hello.World', (exports) ->
# `exports` is where you attach namespace members
exports.hi = -> console.log 'Hi World!'
namespace 'Say.Hello', (exports, top) ->
# `top` is a reference to the main namespace
exports.fn = -> top.Hello.World.hi()
Say.Hello.fn() # prints 'Hi World!'
这一切都很好,但是我在使用 class
关键字执行此操作时遇到了很多麻烦。这样..
namespace 'Project.Something', (exports) ->
exports.something = -> class something
// .. code here
exports.somethingElse = class somethingElse extends something
任何人都可以阐明实现此目的的语法吗?
I found this snippet on the Coffeescript FAQ for creating simplistic namespaces ..
# Code:
#
namespace = (target, name, block) ->
[target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3
top = target
target = target[item] or= {} for item in name.split '.'
block target, top
# Usage:
#
namespace 'Hello.World', (exports) ->
# `exports` is where you attach namespace members
exports.hi = -> console.log 'Hi World!'
namespace 'Say.Hello', (exports, top) ->
# `top` is a reference to the main namespace
exports.fn = -> top.Hello.World.hi()
Say.Hello.fn() # prints 'Hi World!'
That is all well and good, but I am having a great deal of trouble doing this with the class
keyword. Such that ..
namespace 'Project.Something', (exports) ->
exports.something = -> class something
// .. code here
exports.somethingElse = class somethingElse extends something
can anyone shed some light on the syntax that would accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更好的是,类语法允许名称实际上采用成员的形式,因此您实际上可以这样做:
完整的小提琴:http://jsfiddle.net/7Efgd/1/
Even better, the class syntax allows for the name to actually be in the form of a member, so you can actually just do:
Full fiddle here: http://jsfiddle.net/7Efgd/1/
诀窍是首先创建类
,然后在文件末尾附近的某个位置导出所有需要公开的类。
稍后您可以像这样使用这些类:
The trick is to create the class first
Then somewhere near the end of the file export all the classes than need to be exposed.
Later on you can use the classes as so:
使用这样的东西怎么样?
How about using something like this?