Object.getOwnPropertyDescriptors(Node.prototype) 失败

Object.getOwnPropertyDescriptors(Node.prototype) fails

我在 运行 javascript 的网页上记录我的错误,我看到以下代码:

JSON.stringify(
      Object.getOwnPropertyDescriptors(Node.prototype)
    );

失败:

undefined is not a function

对此有何解释?我假设当页面不是在普通浏览器上而是通过使用 WebView 加载时会发生这种情况。

我打开了一个 Android 模拟器,并在普通浏览器和 WebView 测试应用程序上验证了此页面 - 它工作正常。

我还能做些什么来调试它?这个错误经常出现。

编辑

我添加了更多日志记录并检查了以下内容:

Object.getOwnPropertyDescriptor(Node.prototype, "childNodes");
Object.getOwnPropertyDescriptor(Node.prototype, "parentNode");
Object.getOwnPropertyDescriptor(Node.prototype, "hasChildNodes");

并且只有 hasChildNodes 返回一个值。

在您的代码运行的某些 browser/webview 品牌或版本上,JSON.stringify 或(更有可能)Object.getOwnPropertyDescriptors 未定义(添加了前者在 ES5 中,后者最近在 ES2017 中)。

What else can I do to debug it?

添加测试并记录用户代理字符串:

if (!JSON.stringify) {
    /* ...log that `JSON.stringify` isn't supported, w/`navigator.userAgent`...*/
} else if (!Object.getOwnPropertyDescriptors) {
    /* ...log that `Object.getOwnPropertyDescriptors` isn't supported, w/`navigator.userAgent`...*/
} else {
    /* ...log `JSON.stringify(Object.getOwnPropertyDescriptors(Node.prototype))` ... */
}

在您提出的评论中:

So do you know of a way in which I could get the getter function childNodes of the Node.prototype in whichever browser? In all my tests (mobile emulators and browsers) it is always an "own" property of the Node.prototype.

如果您在某些不寻常的实现中看到 undefined 对应 Object.getOwnPropertyDescriptor(Node.prototype, "childNodes"),您可能必须使用 Object.getPrototypeOf 循环查找它在继承链中的位置:

function getDescriptor(obj, name) {
    let descr;
    while (obj && !(descr = Object.getOwnPropertyDescriptor(obj, name))) {
        obj = Object.getPrototypeOf(obj);
    }
    return descr;
}

然后你会使用 const childNodesDescriptor = getDescriptor(Node.prototype, "childNodes"); 或类似的。

但请注意,像 Node.prototype 这样的主机提供的对象也可以违反一些(但不是全部)规则。您可能不得不考虑到在某些实现中您无法获得 getter.

的可能性