In all the articles it is written that JavaScript is a prototype-based language, meaning that every object has a prototype (or, more precisely, prototype chain).
So far, I've tried the following code snippet:
var F = function(); F.prototype.member1 = 1; var object1 = new F(); console.log(object1.member1); // prints 1
How can I access the prototype object of object1
? Is there a browser-neutral way to do that (I mean, not relying on __proto__
property? Seen this link, but maybe there are new developments since 2010) If I can't, could you share please the rationale behind the hood?
As you can see in the above example, Function's prototype property can be accessed using <function-name>. prototype. However, an object (instance) does not expose prototype property, instead you can access it using __proto__ .
The Object. getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.
A prototype is an existing inbuilt functionality in JavaScript. Whenever we create a JavaScript function, JavaScript adds a prototype property to that function. A prototype is an object, where it can add new variables and methods to the existing object.
var f = function(); var instance = new f();
If you know name of instance
class function, you can simply access prototype as:
var prototype = f.prototype; prototype.someMember = someValue;
If you don't:
1)
var prototype = Object.getPrototypeOf(instance); prototype.someMember = someValue;
2) or
var prototype = instance.__proto__; prototype.someMember = someValue;
3) or
var prototype = instance.constructor.prototype; // works only if constructor is properly assigned and not modified prototype.someMember = someValue;
For compatibility you can place into your code the following snippet (and use always Object.getPrototypeOf(instance)
to return prototype):
if(!Object.getPrototypeOf) { if(({}).__proto__ === Object.prototype && ([]).__proto__ === Array.prototype) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__; }; } else { Object.getPrototypeOf = function getPrototypeOf(object) { // May break if the constructor has been changed or removed return object.constructor ? object.constructor.prototype : void 0; }; } }
UPDATE:
According to ECMA-262 6th Edition (June 2015) __proto__
property is standardized as additional feature for Web browsers. All latest editions of top browsers supports it now. Read more about __proto__
:
MDN: Object.prototype.__proto__
EDMA-262 6th Edition (June 2015): B.2.2.1 Object.prototype.__proto__
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