我试图在我的CoffeeScript代码中创建一种全局的单例对象:
window.MyLib =
Foos: {}
Bars: {}
Client: ->
@_client ||= (
someVar = 'foo'
new ExpensiveClient(someVar)
)
# ...
MyLib.Client.performSomeAction()
但是,代码实际上要求我这样做:
MyLib.Client().performSomeAction()
如何解决实现惰性实例化的问题而无需使用括号将其作为函数调用?
更新:或者,如果有办法实现某种“方法缺失”,Client
函数可以返回一个将责任委托给实际客户端的对象,但是只在需要时才实例化。
答案 0 :(得分:3)
也许是这样的:
lazyGet = (obj, name, property) ->
Object.defineProperty obj, name, get: property
window.MyLib = do ->
@_client = null
Foos: {}
Bars: {}
lazyGet this, 'Client', ->
@_client ||= (
someVar = 'foo'
new ExpensiveClient someVar
)
答案 1 :(得分:0)
前几天我正在寻找一个单身人士,并在这个网站上找到了答案。 http://coffeescriptcookbook.com/chapters/design_patterns/singleton
这里的代码来自该网站,这可能是您正在寻找的
class Singleton
# You can add statements inside the class definition
# which helps establish private scope (due to closures)
# instance is defined as null to force correct scope
instance = null
# Create a private class that we can initialize however
# defined inside this scope to force the use of the
# singleton class.
class PrivateClass
constructor: (@message) ->
echo: -> @message
# This is a static method used to either retrieve the
# instance or create a new one.
@get: (message) ->
instance ?= new PrivateClass(message)
a = Singleton.get "Hello A"
a.echo() # => "Hello A"
b = Singleton.get "Hello B"
b.echo() # => "Hello A"
Singleton.instance # => undefined
a.instance # => undefined
Singleton.PrivateClass # => undefined