有没有办法让lodash复制属性getter和setter?

时间:2015-12-17 06:04:45

标签: javascript node.js lodash

在以下情况中,我发现lodash似乎没有复制源对象的getter:

const _ = require("lodash");

let sourceObject = { };
Object.defineProperty(sourceObject, "abc", {
    get: () => 123
});

let cloneObject = _.cloneDeep(sourceObject);

console.log(sourceObject.abc); // 123
console.log(cloneObject.abc);  // undefined

有没有办法通过lodash模块实现上述目标?

1 个答案:

答案 0 :(得分:-2)

很抱歉迟到了,但我觉得这个记录应该得到适当的解决方案,因为我刚刚为自己解决了这个问题:

const hasGetter = (obj, prop) => !!Object.getOwnPropertyDescriptor(obj, prop)['get']
const copyProperty = (obj1, obj2, propName) => Object.defineProperty(obj2, propName, Object.getOwnPropertyDescriptor(obj1, propName))
const copyObject = (obj) => Object.keys(obj).reduce((a, x) => copyProperty(obj, a, x), {})

// DEMO
let from = {
    one: 1,
    two: "two"
}

// define a getter
Object.defineProperty(from, "seconds", {
    get: function() {
        return (new Date()).getSeconds()
    },
    enumerable: true
})

const to = copyObject(from)

// prove it worked
let count = 0
let id = setInterval(() => {
    console.log(hasGetter(to, "seconds"), to.seconds)
    count++
    if (count > 5) clearInterval(id)
}, 1000)