我创建了一个我想扩展的单例类。它(一半)的工作原理是它只创建类的单个实例,但添加到子类的属性是未定义的。这是原始的单例:
class Singleton
_instance = undefined
@getInstance: ->
if _instance is undefined
console.log 'no instance exists, so create one'
_instance = new _Singleton()
else
console.log 'an instance already exists.'
class _Singleton
constructor: ->
console.log 'new singelton'
module.exports = Singleton
这是子类:
Singleton = require('./singleton')
class Stinky extends Singleton
constructor: ->
var1 : 'var1'
module.exports = Stinky
现在,如果我在我的 Node 应用程序中使用以下内容:
Stinky = require './stinky'
thing1 = Stinky.getInstance()
thing2 = Stinky.getInstance()
console.log "Thing var1: #{thing1.var1}"
getInstance() 方法的行为符合预期,但 var1 未定义。如果我在非单例类上做同样的事情,它们就可以正常工作。谢谢。
最佳答案
我稍微精简了您的代码。这是剩下的 2 个类:
class Singleton
@_instance: null
@getInstance: ->
@_instance or= new @( arguments... )
class Stinky extends Singleton
constructor: ( @num ) ->
thing1 = Stinky.getInstance( 1 )
thing2 = Stinky.getInstance( 2 )
console.log( thing1.num, thing2.num )
我做了以下更改:
- 合并单例和_单例
- 将 _instance 更改为 @_instance 以便它可以附加到 Singleton 而不是其原型(prototype)
- 在 getInstance 中添加参数 splat(以防需要参数)
- 将 getInstance() 指向扩展对象而不是单例
在这个例子中,我使用了 2 个不同的数字来确保第二个构造函数从未被调用。
关于class - 如何创建 coffeescript 单例子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10142413/