2

http://stacksnippets.net/scripts/snippet-javascript-console.js uses this function

function getProps(obj) {
    var props = [];

    do {
        for (var prop in obj) {
            if (props.indexOf(prop) === -1) {
                props.push(prop);
            }
        }
    }
    while (obj = obj.__proto__);

    return props;
}

That is wrong because

  • __proto__ is not standard (is only defined in an annex for compatibility), and thus should be avoided. Moreover, not all objects inherit __proto__ from Object.prototype.
  • for...in loops already iterate inherited properties.

See the redundancy:

function getProps(obj) {
  var i = 0;
  do {
    var current = [];
    for (var prop in obj) current.push(prop);
    console.log('Iteration ' + ++i + ': ' + JSON.stringify(current.sort()));
  } while (obj = obj.__proto__);
}
var a = {};
a.a = 'a';
var b = Object.create(a);
b.b = 'b';
var c = Object.create(b);
c.c = 'c';
var d = Object.create(c);
d.d = 'd';
getProps(d);

Instead, the function should be

function getProps(obj) {
    var props = [];
    for (var prop in obj) {
        props.push(prop);
    }
    return props;
}

Or just use the ES5 Object.keys function, as proposed in The console should not display inherited properties.

2
  • @AlexanderO'Mara Note Object.keys only returns own properties. I think that would be better, but people could disagree. Commented Jun 12, 2016 at 22:28
  • Yeah, that's true. I wonder if perhaps it was implemented this way to order the properties based on inheritance. Commented Jun 12, 2016 at 22:42

1 Answer 1

3

This has been done and will be out in the next deployment. Please ping me in a comment here if you find any problem with the solution.

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.