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

Defining a property getter for my singleton class in CoffeeScript

本文关键字:定义 属性 getter 单例类 我的 CoffeeScript      更新时间:2023-09-26

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

###
# 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

在一个文件中,我有下面的两个类,折叠和_折叠,后者被隐藏,只有前者导出(命名空间)到全局。

###
  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

我不能调用fold . factory .create(),因为fold。

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

console.log 'Factory' of Folds

这不是核心问题,虽然:核心问题是,你正在使用的public方法实际上定义了一个属性与给定的名称上的类原型,作为行

Object.defineProperty @prototype, name, config

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

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

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