Mozilla claimed it would remove __proto__ a while back (~2008) and it is still in the browser. Is it still going to be deprecated? It works in Opera, (Safari I think) and Chrome as well. I don’t need to worry about IE so I would love to keep using it.
However, I don’t want my code to stop working one day, so on to my question:
__proto__ allows for dead simple inheritance:
a.__proto__ = {'a':'test'}
Is there anyway I can replicate this in a standards compliant way? I know there is functional inheritance, that’s ugly, and it over-complicates the fact that I just want to create a prototype chain. Just wondering if any wizards have solved this.
Thanks
Note: It’s considered a bad practice to change the value of
__proto__. Doing so is strongly discouraged by Brendan Eich, the creator of JavaScript, amongst others. In fact the__proto__property has been removed entirely from a few JavaScript engines like Rhino. If you wish to know why then read the following comment by Brendan Eich.Update: Browsers are not going to remove the
__proto__property. In fact, ECMAScript Harmony has now standardized both the__proto__property and thesetPrototypeOffunction. The__proto__property is only supported for legacy reasons. You are strongly advised to usesetPrototypeOfandgetPrototypeOfinstead of__proto__.Warning: Although
setPrototypeOfis now a standard, you are still discouraged from using it because mutating the prototype of an object invariably kills optimizations and makes your code slower. In addition, the use ofsetPrototypeOfis usually an indication of poor quality code.You don’t need to worry about your existing code not working one day. The
__proto__property is here to stay.Now, for the question at hand. We want to do something similar to this in a standards compliant way:
Obviously you can’t use
Object.createto achieve this end since we are not creating a new object. We are just trying to change the internal[[proto]]property of the given object. The problem is that it’s not possible to change the internal[[proto]]property of an object once it’s created (except via using__proto__which we are trying to avoid).So to solve this problem I wrote a simple function (note that it works for all objects except for functions):
So we can now change the prototype of any object after it’s created as follows (note that we are not actually changing the internal
[[proto]]property of the object but instead creating a new object with the same properties as the given object and which inherits from the given prototype):Simple and efficient (and we didn’t use the
__proto__property).