这是我为在我的类中创建属性而定义的辅助函数:
###
# 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 未定义。
最佳答案
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
实例的属性可用。
关于javascript - 在 CoffeeScript 中为我的单例类定义属性 getter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8422550/