Object.assign(...)尝试在没有setter的情况下设置属性

时间:2017-04-11 19:53:56

标签: javascript

当在对象上专门定义get-only属性,然后尝试在原始对象上分配另一个对象时,Object.assign似乎并不关心目标属性是否为只读:

var myObj = {
    firstName: "Jimbo",
  lastName: "Smythe"
};

Object.defineProperty(myObj, "fullName", {
    get: function () {
    return this.firstName + " " + this.lastName;
  }
});

Object.assign(myObj, {
  fullName: "Jimbo T. Smythe"
});

这会导致以下异常:

  

TypeError:无法设置只有getter

的#的属性fullName

这不是Object.assign中的错误吗?

此处的完整示例:https://jsfiddle.net/fa8j7p5j/

1 个答案:

答案 0 :(得分:0)

所以我认为这里的真正问题是以前的Object.assign从来没有这样的情况可能导致异常。现在是因为存在只读属性。现在无法对两个未知对象盲目使用assign,因为它可能会爆炸。

不幸的是,在添加新的Object.assignSafe方法之前,解决此问题的唯一方法是防止这些不良属性。

/**
 * This function performs an Object.assign but does not explode on trying to set a read-only property
 * @param  {Object} target  Target to apply sources properties to
 * @param  {Array<Object>} sources Any number of sources to be applied to target
 * @return {Object}        The updated target object;
 */
function assignSafe(target, ...sources) {
    const proto = Object.getPrototypeOf(target);
    const safe = sources.map(source => {
        let entries = Object.entries(source);
        let reduced = entries.reduce((accumulator, currentValue) => {
            const descriptor = Object.getOwnPropertyDescriptor(proto, currentValue[0]);
            if (!descriptor || descriptor.set) {
                accumulator.push(currentValue);
            }
            return accumulator;
        }, []);
        return Object.fromEntries(reduced);
    });
    return Object.assign(target, ...safe);
}