Is there a difference between Object.getPrototypeOf(obj)
and obj.constructor.prototype
? Or are these two referencing the same thing?
Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
So what's the difference between constructor and prototype? A short answer is that the constructor is a function that is used to create an object, while the prototype is an object that contains properties and methods that are inherited by objects created from a constructor.
The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.
In JavaScript, an object can inherit properties of another object. The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.
NO
It returns the internal [[Prototype]]
value.
For example:
var o = Object.create(null);
Object.getPrototypeOf(o); // null
o.constructor.prototype; // error
var p = {};
var o = Object.create(p);
Object.getPrototypeOf(o); // p
o.constructor.prototype; // Object.prototype
o.constructor.prototype
only works with objects created through new ConstructorFunction
or where you have manually set the Prototype.prototype.constructor === Prototype
relationship.
No. In particular, the constructor
property of an object is not always set to what you would consider "correct."
An example of where getPrototypeOf
works but .constructor.prototype
does not:
function F() { }
F.prototype = {
foo: "bar"
};
var obj = new F();
assert.equal(obj.constructor.prototype, Object.prototype);
assert.equal(Object.getPrototypeOf(obj), F.prototype);
It also fails for typical prototypal inheritance scenarios:
// G prototypally inherits from F
function G() { }
G.prototype = Object.create(F.prototype);
// or: G.prototype = new F();
var obj2 = new G();
assert.equal(obj2.constructor.prototype, Object.prototype);
assert.equal(Object.getPrototypeOf(obj2), G.prototype);
assert.equal(Object.getPrototypeOf(Object.getPrototypeOf(obj2)), F.prototype);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With