Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting __proto__ on object without initial prototype

Let us create new object, and then change its prototype:

var obj = new Object;
obj.__proto__ = new Date;
obj.setTime // is a function

We see that obj now inherits properties from its new prototype, new Date.

Then, we create new object without prototype and change its prototype:

var obj = Object.create(null);
obj.__proto__ = new Date;
obj.setTime // undefined

We see that prototype chain doesn't work - obj didn't inherit properties from new Date, even though its __proto__ is new Date.

Why?

(I guess it's because Object has some internal logic in setter of __proto__ property, but not sure)

like image 614
Albert Gufranov Avatar asked Apr 10 '26 01:04

Albert Gufranov


1 Answers

This is one subtle difference between __proto__ and Object.getPrototypeOf() / Object.setPrototypeOf() when we need to explicitly access / modify the prototype of an object.

This is one of the reasons why i have convinced myself that we should use Object.setPrototypeOf() and Object.getPrototypeOf() in the place of __proto__.

var o = Object.create(null);
Object.setPrototypeOf(o, new Date());
console.log(o.setTime)
like image 55
Redu Avatar answered Apr 11 '26 15:04

Redu