扩展具有隐藏属性的对象

extend an object with hidden properties

我有以下 coffeescript class

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,但我 想要 meta 当我使用 for 循环在新对象 x 上循环时出现。

如果我未能正确解释这一点,请告诉我,我会努力做得更好:)

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}

您可以使用 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}