我有以下coffeescript类
class Data
constructor: (data)->
data.prototype.meta = @meta
return data
meta: ->
return { id: 123 }
# this is how I want to work with it, as an example
a = {name: "val"}
x = new Data a
for key, item of x
console.log key, item ## should say `name`, `val` (not meta)
console.log x.meta ## should say `{id:123}
我想将meta
属性添加到现有object
,但是当我循环播放时, NOT 希望meta
出现使用for循环的新对象x
。
如果我没有正确解释这个问题,请告诉我,我会尽力做得更好:)
答案 0 :(得分:1)
您可以使用Object.defineProperty():
class Data
constructor: (data) ->
Object.defineProperty(data, "meta", { enumerable: false, value: @meta });
return data
meta: { id: 123 }
a = {name: "val"}
x = new Data(a)
for key, item of x
console.log key, item ## should say `name`, `val` (not meta)
console.log x.meta ## should say `{id:123}
答案 1 :(得分:0)
A最终使用以下内容......
a = {name: "val"}
a.meta = {id: 123} ## as normal
Object.defineProperty a, "meta", enumerable: false ## this hides it from loops
for key, item of x
console.log key, item ## should say `name`, `val` (not meta)
console.log x.meta ## should say `{id:123}