在CoffeeScript中为我的singleton类定义属性getter

时间:2011-12-07 21:07:49

标签: javascript singleton coffeescript getter

这是我为在类中创建属性而定义的辅助函数:

###
# defines a property on an object/class
# modified from https://gist.github.com/746380
###
Object::public = (name, options = {}) ->
  options['default'] ?= null
  variable = options['default']
  getter = if typeof options['get'] is 'function' then options['get'] else -> variable
  setter = if typeof options['set'] is 'function' then options['set'] else (value) ->  variable = value

  config = {}
  config['get'] = getter if options['get']
  config['set'] = setter if options['set']
  config['configurable'] = no
  config['enumerable'] = yes

  Object.defineProperty @prototype, name, config

在文件中我有以下两个类,Folds和_Folds,后者只被隐藏,只有前者导出(命名空间)到全局。

###
  Public exported fetcher for fold factory,
  being the only way through which to create folds.
###
class Folds
  _instance = undefined

  # static fetch property method
  @public 'Factory',
    get: -> _instance ?= new _Folds

###
  Encapsuled singleton factory for one-stop fold creation
###
class _Folds
  constructor: ->

  create: -> new Fold

然后当我尝试这个时,它返回false。为什么呢?

console.log 'Factory' of Folds

以下是返回“function Folds(){}”

console.log Folds

我无法调用Folds.Factory.create(),因为Folds.Factory未定义。

1 个答案:

答案 0 :(得分:2)

CoffeeScript的in用于数组(和类似数组的对象); of编译为JavaScript的in。所以你想要的是

console.log 'Factory' of Folds

但这不是核心问题:核心问题是您使用的public方法实际上定义了类' prototype 上具有给定名称的属性,因为线

Object.defineProperty @prototype, name, config

告诉我们。所以真正想要的是

console.log 'Factory' of Folds.prototype  # should be true

这意味着Factory方法将作为每个Folds实例的属性提供。