Val
Val

Reputation: 17542

extend an object with hidden properties

I have the following 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}

I would like to add the meta property to an existing object, but I do NOT want the meta to come up when I loop on the new object x using a for loop.

If I have failed to explain this properly please let me know I will try and do better :)

Upvotes: 0

Views: 45

Answers (2)

mutil
mutil

Reputation: 3305

You can use 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}

Upvotes: 1

Val
Val

Reputation: 17542

A ended up using the following...

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}

Upvotes: 0

Related Questions