2015-06-05 157 views
0

我有以下的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,但我希望meta上來時,我環路在新對象x上使用for循環。

如果我沒能解釋這個正確,請讓我知道我會盡量做的更好:)

回答

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} 
0

一個最終使用下面...

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}