The __proto__
comes from the constructor's prototype
.
In the first case, One
is your constructor. You haven't assigned anything to One.prototype
, so it defaults to a Object
's __proto__
and you get the two levels of inheritance.
If you had added things to that object, they would show up as part of the One
prototype.
function One() {
this.x = 4;
this.y = 'hhh';
}
One.prototype.z = 'foobar';
var one = new One();
In the second case, you are creating an object literal which has Object
as it's prototype, so you only inherit from the Object
prototype. Prototypes are objects themselves, so if you were to add properties to it, like so:
foo.__proto__.z = 'foobar';
You are modifying the instance of Object that is foo
's prototype, it doesn't modify Object
itself, only that particular instance of it. That is what the article means, by foo
's prototype.
I just did a test in V8 and it seems an object literal doesn't have an instance of Object
as it's prototype, it has Object
's __proto__
itself, so you should not modify foo.__proto__
, you would be modifying the underlying Object
prototype that all Objects inherit from. If you do wish do modify it, you should create a new instance of Object
first to add to:
foo.__proto__ = {};
foo.__proto__.z = 'foobar';
Example:
var x = {};
x.__proto__ = {};
x.__proto__.z = 'foobar';
var y = {};
y.z; // undefined
Object.z; // undefined
vs.
var x = {};
x.__proto__.z = 'foobar';
var y = {};
y.z; // 'foobar'
Object.z; // 'foobar'
In my opinion, it would be better if object literals automatically created a new instance of Object for their __proto__
. Then again, there is no real reason in modifying the prototype of an object literal.
Also note that you should not use __proto__
directly, as it is deprecated, and its future replacement is strongly discouraged as well. You should use Object.create for implementing inheritance in Javascript.