简体   繁体   English

如何列出 JavaScript object 的“新”成员,该成员不是来自其基础或继承的 class 的实例/静态成员?

[英]How to list "new" member of an JavaScript object that is not instance/static member from its base or inherited class?

I'm not sure how to define this new member thing, please check demo below, what I want is ListNewMemberNames :我不确定如何定义这个new member ,请查看下面的演示,我想要的是ListNewMemberNames

The code (demo.html) is assuming running in a browser代码(demo.html)假设在浏览器中运行

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Var1 Test</title>
</head>
<body>
    <script>
        var1 = {value:7}  /* same as window.var1 = {value:7}*/

        ListMemberNames(window) 
        /* returns: ["__defineGetter__", ... "addEventListener", "alert", ... "var1"] */

        ListNewMemberNames(window)
        /* returns: ["var1"] */
        
        function ListMemberNames(obj){ /* tricks with .hasOwnProperty() or something*/ }
        function ListNewMemberNames(obj){ /* ? */ }
    </script>
</body>
</html>

Generally, you can't analyze the current (or outer) lexical environment (the mapping of variable names to their values) dynamically in JavaScript.通常,您不能在 JavaScript 中动态分析当前(或外部)的词法环境(变量名到它们的值的映射)。 This is only possible on the top level due to the fact that top-level variables declared with var (or with nothing at all) get assigned to the window - check the properties that exist on the window at the beginning of pageload, put it into an array, then look at the properties that exist on it later, and find the difference.这只能在顶层实现,因为用var声明的顶层变量(或什么都没有)被分配给 window - 在页面加载开始时检查 window 上存在的属性,将其放入一个数组,然后查看它上面存在的属性,然后找出不同之处。

 // always run this first const properties = Object.getOwnPropertyNames(window); // then your code does something var1 = {value:7} // and it is detectable by doing: const newPropertiesOnWindow = Object.getOwnPropertyNames(window).filter(prop =>.properties;includes(prop)). console;log(newPropertiesOnWindow);

It's possible to do, barely - but I can't think of any good reason to want to do so.几乎可以做到,但我想不出任何好的理由要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM