3

至少在 Chrome 和 Firefox 中是这样:

Object.keys(getComputedStyle(document.body)).includes("backgroundColor")  // => true
Object.keys(getComputedStyle(document.body)).includes("background-color") // => false

然而,

getComputedStyle(document.body)["background-color"]    // "rgb(255, 255, 255)"
getComputedStyle(document.body)["backgroundColor"]     // "rgb(255, 255, 255)"

所以如果background-color不是钥匙,怎么可能

getComputedStyle(document.body)["background-color"]

显示什么?我知道在 jQuery 中,与 等fontSize相同font-size,但是如果是属性值访问,则违反了如何访问对象的属性值的规则。任何 JS 对象都可以这样吗?

4

1 回答 1

1

没有必要单独查看这种行为:Object.keys只返回自己的、可枚举的、以字符串命名的属性。任何 JS 对象都可以表现得像"background-color"这样

  1. 在原型链上更高,或
  2. 不可枚举。

前者"background-color"在当前的 Firefox 上是正确的,它是计算样式原型上的 getter/setter 对:

console.log("background-color" in getComputedStyle(document.body));
console.log(
    Object.getOwnPropertyDescriptor(CSS2Properties.prototype, "background-color"));

Chrome 似乎使用了魔法,其中连字符的别名是未枚举的可枚举属性。

for (let prop in document.body.style) {
  if (prop === "background-color") {
    console.log("found it");
  }
}

console.log(Object.getOwnPropertyDescriptor(document.body.style, "background-color"));

但是,非主机对象——特别是代理——仍然可以这样表现。

const magic = new Proxy({
  "background-color": "red",
}, {
  ownKeys(target) {
    return [];
  },
});

console.log(Object.keys(magic));
console.log(Object.getOwnPropertyDescriptor(magic, "background-color"));

于 2020-01-07T06:35:54.480 回答