在 JavaScript 中,有原生对象和宿主对象。通常,您可以依赖诸如Object.keys
使用本机对象之类的东西,但不能使用宿主对象。window
, document
, 和其他是宿主对象。尤其是 IE,它的宿主对象不是原生的(宿主函数没有call
orapply
特性等)而闻名。
或者,当然,它可能document
没有可枚举的属性。对象的大多数默认属性都是不可枚举的,因此不会出现在Object.keys
. 例如,Object.keys([]).length
和Object.keys(new RegExp(".*")).length
都是0
因为它们都没有任何可枚举的属性,即使它们都有很多属性(它们的所有“方法”都有属性,当然空白数组有一个length
属性,而空白数组也RegExp
有一个lastIndex
属性)。
更新:事实上,这是可数的事情。试试这个测试:
alert(Object.keys(window.document).length);
window.document.AAA__expando__property = "foo";
alert(Object.keys(window.document).length);
对我来说,在 IE9 上,这些警报分别是“0”和“1”。所以window.document
supports Object.keys
,只是window.document
默认情况下没有任何可枚举的属性。(相比之下,在 Chrome 上,我一开始就有 65 个可枚举属性,当然,一旦我添加了我的 expando,就有 66 个。)
这是一个更完整的测试页面(实时副本)(快速组合在一起,而不是美丽的东西):
window.onload = function() {
document.getElementById('theButton').onclick = function() {
if (typeof Object.keys !== 'function') {
display("<code>Object.keys</code> is not a function");
return;
}
showKeys("Before adding", Object.keys(window.document));
window.document.AAAA__expando__foo = "bar";
showKeys("After adding", Object.keys(window.document));
};
function showKeys(prefix, keys) {
var p, ul;
keys.sort();
prefix =
"[" + prefix +
"] Keys on <code>window.document</code> (" +
keys.length +
")";
if (keys.length !== 0) {
prefix += " (click to toggle list)";
}
p = display(prefix);
if (keys.length !== 0) {
ul = document.createElement("ul");
ul.innerHTML = "<li>" + keys.join("</li><li>") + "</li>";
ul.style.display = "none";
document.body.appendChild(ul);
p.onclick = function() {
ul.style.display =
(ul.style.display === "none") ? "" : "none";
};
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
return p;
}
};