我想要一个带有方法和私有(private)变量的代理对象。
也就是说,所有普通的对象属性:
foo = {}
foo.bar = "baz"
foo.boo = "hoo"
一些原型(prototype):
foo.setPrivateThings = function(value){ if (value) private = value; return private; }
其中枚举跳过私有(private)变量/函数:
console.log(foo); // { bar: "baz", boo: "hoo" }
get/set 将通过一个神奇的 getter/setter 运行:
foo.doesntexist = "..." = function(key){ console.log "Setting "+key; return new Date(); }
到目前为止,我有这个使用 Node 代理的 hokey Coffeescript。还有更好的答案吗?
class Data
constructor: (obj) ->
@proxy = require "node-proxy"
p = @proxy.create
has: (name) ->
name of obj
hasOwn: (name) ->
({}).hasOwnProperty.call obj, name
get: (receiver, name) ->
p = obj.transform()[name]
if typeof p != 'undefined' && p != '__lookupGetter__' && p != '__lookupSetter__'
return p()
# We could do magic getting here
obj[name]
set: (receiver, name, val) ->
# We could do magic setting here
obj[name] = val
true
enumerate: ->
result = []
for name of obj
result.push name if typeof obj[name] != 'function'
result
keys: ->
Object.keys obj
, obj
_transform = {}
p.transform = (_t) ->
_transform = _t if _t
return _transform
return p
d = new Data
name: "Bill"
colors: ["blue", "red"]
d.transform
timer: ->
return new Date()
console.log d.name, d.colors, d.timer
console.log d
产生
Bill [ 'blue', 'red' ] Sat, 15 Oct 2011 06:39:27 GMT
{ name: 'Bill', colors: [ 'blue', 'red' ] }
最佳答案
where enumeration skips private variables/functions:
Object.defineProperty(foo, "name", {
get: function () { "return magic"; },
set: function (value) { setMagic(value); },
writable: true,
configurable: true
enumerable: false
});
代理是矫枉过正,只定义不可枚举的属性
关于Javascript 代理 : node-proxy, 和谐,混合对象与神奇的 getter 和 setter ......在 Coffeescript 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7776285/