本文介绍了Coffeescript“命名空间"中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Coffeescript 常见问题解答中找到了这个片段,用于创建简单的命名空间 ..
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!'
这一切都很好,但是我在使用 class
关键字时遇到了很多麻烦.这样..
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?
推荐答案
诀窍是先创建类
class MyFirstClass
myFunc: () ->
console.log 'works'
class MySecondClass
constructor: (@options = {}) ->
myFunc: () ->
console.log 'works too'
console.log @options
然后在文件末尾附近的某个地方导出所有需要公开的类.
Then somewhere near the end of the file export all the classes than need to be exposed.
namespace "Project.Something", (exports) ->
exports.MyFirstClass = MyFirstClass
exports.MySecondClass = MySecondClass
稍后你可以像这样使用这些类:
Later on you can use the classes as so:
var firstClass = new Project.Something.MyFirstClass()
firstClass.myFunc()
var secondClass = new Project.Something.MySecondClass
someVar: 'Hello World!'
secondClass.myFunc()
这篇关于Coffeescript“命名空间"中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!