Hm… is it a bug or a feature though? ^^ When specifying a value here it does not appear in console.dir(), only with a getter; this does indeed seem a bit arbitrary. The specs are not clear on that matter either, they just state that
The printer operation is implementation-defined.
So I don’t think there’s a particular reason for that, other than that it is how it is.
Not pointless at all, this is exactly the kind of experimenting that really gets you to know a language IMHO. :-)
I don’t know the authority of the person responding, but it seems to be intended behaviour with console.dir
The spec of console.dir [1] references the object formatting [2] which states “An object with optimally useful formatting is an implementation-specific, potentially-interactive representation of an object judged to be maximally useful and informative.”
While “x” is not an instance field of foo, but on the prototype, you are correct that “x” should technically not show up. Object.hasOwnProperty(foo, "x") will yield false. However, the information is useful, as invoking foo.x is allowed and will yield 3. This is especially prevalent in HTMLElements where various attributes are shown (like id) that live on the prototype.
Therefore, to keep the information useful, we opt to keep showing the information when running console.dir.
Not entirely sold on that. If ‘y’ is a standard property on foo’s prototype, we can still access it using foo.y — in logging it won’t show up on the instance
Anyway that seems to be the score
Simple test
function Shape (sides) {
this.sides = sides
}
Shape.prototype = {
constructor: Shape,
get numSides () {
return this.sides
},
colour: 'red'
}
const sqr1 = new Shape(4)
console.dir(sqr1)
Output:
Shape
numSides: (...) <---
sides: 4
__proto__: v
colour: "red"
constructor: ƒ Shape(sides)
numSides: (...) <---
get numSides: ƒ numSides()
__proto__: Object
console.log(sqr1.numSides) // 4
console.log(sqr1.colour) // red
Ah interesting, a very pragmatic approach then. I would tend to agree with their reasoning regarding HTMLElements; and the getters are displayed in the same colour as the prototype after all. Anyway thx for that link! :-)