Quoting from __proto__
's MDN Docs,
The __proto__
property is deprecated and should not be used. Object.getPrototypeOf
should be used instead of the __proto__
getter to determine the [[Prototype]] of an object. Mutating the [[Prototype]] of an object, no matter how this is accomplished, is strongly discouraged, because it is very slow and unavoidably slows down subsequent execution in modern JavaScript implementations. However, Object.setPrototypeOf
is provided in ES6 as a very-slightly-preferred alternative to the __proto__
setter.
But your actual code works, let us see why.
First of all, any object which is created with an Object literal will have its __proto__
property as the same as Object.prototype
. You can check this like this
var object2 = {};
console.log(object2.__proto__ === Object.prototype);
# true
Since object1
is created with MyObject
function, the following is true
console.log(object1.__proto__ === MyObject.prototype);
# true
When you say
object2.__proto__ = object1.__proto__;
From 2, we can see that it is the same as,
object2.__proto__ = MyObject.prototype;
so, you are just making JavaScript believe that, object2
is also an object of MyObject
.
Since we assigned MyObject
's prototype to object1
's prototype, constructor
of both the objects are the same
console.log(object1.constructor === object2.constructor);
And then you are calling the MyObject
function with object2
as this
.
object1.constructor.call( object2, 'bar' );
Since changing __proto__
is NOT recommended, the best way to do this would be to use new
keyword only
var object1 = new MyObject('foo'),
object2 = new MyObject('bar');
But, lets say you have got only object1
, but not the definition of MyObject
. Then, you can make use of the constructor
property like this
object2 = new object1.constructor('bar');