1

在 Node.js 中,当迭代对象的属性时,它是在它自己的属性之前迭代继承的属性还是反过来?

这也可能在未来发生变化,我是否需要为此编写一些功能检测,如下所示?

var util = require("util");

function testOwnFirst () {
    function A () {
        this.a = 1;
    }

    function B () {
        this.b = 2;
    }
    util.inherits(B, A);

    var objB = new B();
    for (var prop in objB) {
        if(prop === "a") {
            // Traversal starts with inherited properties first
            return false;    
        }
            // Traversal starts with own properties first
        return true;
    }
}

exports.ownFirst = testOwnFirst();
4

1 回答 1

1

ECMAScript 标准非常清楚地指出对象是一个无序的属性集合(请参阅此处的第 4.3.3 节:ecma-international.org/publications/files/ECMA-ST-ARCH/...),因此您不应以任何方式依赖属性的排序。Node(和底层的 V8 引擎)不会为您提供任何保证。

最好的方法是迭代所有属性并调用 hasOwnProperty() 来查看哪些是继承的,哪些不是

于 2013-09-29T09:35:20.560 回答