Javascript代理:node-proxy, Harmony,带魔法getter和setter的混合对象.Coffe
Javascript proxies: node-proxy, Harmony, mixed objects with magic getters and setters... in Coffeescript?
我想有一个代理对象与方法和私有变量附加到它。
也就是说,所有正常的对象属性:
foo = {}
foo.bar = "baz"
foo.boo = "hoo"
和一些原型:
foo.setPrivateThings = function(value){ if (value) private = value; return private; }
枚举跳过私有变量/函数:
console.log(foo); // { bar: "baz", boo: "hoo" }
和get/set将通过一个魔法getter/setter来运行:
foo.doesntexist = "..." = function(key){ console.log "Setting "+key; return new Date(); }
到目前为止,我有这个虚假的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' ] }
枚举跳过私有变量/函数:
Object.defineProperty(foo, "name", {
get: function () { "return magic"; },
set: function (value) { setMagic(value); },
writable: true,
configurable: true
enumerable: false
});
代理是多余的,只需定义不可枚举的属性
感谢@Raynos,我认为这个解决方案可能是合适的(将尝试更多):
obj =
firstname: "Bill"
lastname: "Fell"
colors: ["blue", "red"]
transform =
name: ->
"#{this.firstname} #{this.lastname}"
colorstoo: "colors"
for key, val of transform
Object.defineProperty obj, key,
get: if typeof val == "string" then new Function("return this.#{val}") else val
enumerable: true
console.log obj.name, obj.colorstoo
console.log obj
生产:
Bill Fell [ 'blue', 'red' ]
{ firstname: 'Bill',
lastname: 'Fell',
colors: [ 'blue', 'red' ],
name: [Getter],
colorstoo: [Getter] }
注意这个解决方案不允许动态get/set,只定义为一个列表。
相关文章:
- 混合 ui-sref 和 $state.go 在 Angular ui-router 中进行状态转换
- "实例范围”;TypeScript类的getter/setter
- 混合元素的有角度的ng重复
- VueJS多个混合
- 如何对混合格式的数字(89900,1k,1.5k,15.2k)进行排序
- 访问者:setter不起作用
- 过滤”;溢价;页面加载选项使用混合
- 将javascript与PHP混合?(跟踪Google Analytics虚拟页面浏览量)
- 在混合基本 URL 下动态加载 require.js 模块
- 如何防止在javascript中执行继承属性的getter-setter方法
- javascript散列/数组混合性能
- 如何通过ibmworklight中的sql适配器从db2中检索或显示html页面上的数据?android混合应用程序开发
- JavaScript 对象中的私有成员,带有 getter 和 setter
- localStorage-对象的getter-, setter-方法的目的是什么?
- 如何在 VB 项目中混合使用 Razor 和 Javascript
- 混合类型提前.js和引导 3.
- 传递参数时如何避免模块模式中的 getter/setter 函数
- 混合 Web/客户端框架
- 如何在树枝模板中包含已解释和未解释文本的混合
- Javascript代理:node-proxy, Harmony,带魔法getter和setter的混合对象.Coffe