getBoundingClientRect() 对象属性不可复制

getBoundingClientRect() Object properties cannot be copied

function test(o) {
    console.log("Object:", o);
    console.log("Assign test:", Object.assign({}, o));
    console.log("Keys test:", Object.keys(o));
    console.log("JSON test:", JSON.stringify(o));
}

var el = document.getElementById("question");                 /* or document.body */

test(el.style);                                               /* works as expected */
test(el.getBoundingClientRect());                             /* behaves like {} */
test(Object.assign(el.getBoundingClientRect(),{aaaa: 1111})); /* works... only for aaaa */

为什么?

输出(测试结果)

参见PasteBin

MDN 文档

  1. Element.getBoundingClientRect()
  2. DOMRect

Object.assignObject.keys 正在使用 own 可枚举属性。 DOMRect 属性继承自 DOMRectPrototype,这些方法无法访问。

你可以证明:

let rect = el.getBoundingClientRect();
rect.hasOwnProperty('x');                        // === false
Object.getPrototypeOf(rect).hasOwnProperty('x'); // === true

我使用 Lodash _.assignIn 迭代 拥有和继承 源属性:

https://jsfiddle.net/msazmfxo/

更新

根据这个答案, the acceptable solution

var ownify = input => 
               Object.keys(Object.getPrototypeOf(input)).reduce((output,key) => 
                 Object.assign(output, {[key]: input[key]}), Object.assign({}, input));

test(ownify(el.getBoundingClientRect())); /* apparently works! */

(虽然只迭代了一层继承,但更深层次的属性仍然会丢失)