2015-06-05 117 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}