In JavaScript, where do prototype's functions hide when we instantiate the derived object?-Collection of common programming errors
I am currently trying to figure out exactly how the prototypical inheritance works in JavaScript. Here is the mystery I currently trying to solve.
Suppose we set up the following structure:
var base = { greet : "hello" }
var child = function () {}
child.prototype = base;
child.prototype.protoSomething = function () {}
var instance = new child();
Nothing fancy. Now lets see what instance
has for properties (own or otherwise):
for(prop in instance) {
console.log(prop); // prints 'greet', 'protoSomething'
}
Alright, so it has greet
and protoSomething
, are they instance
‘s own members?
for(prop in instance) {
if(instance.hasOwnProperty(prop))
console.log(prop); // nothing is printed
}
Nope, own property list is empty. Are they in instance
‘s prototype?
if(instance.prototype === undefined) {
console.log("'instance' has no prototype"); // gets printed
}
Well, bummer, instance
doesn’t have a prototype assigned. So, if the properties are not own and there is no prototype, where are they coming from? I feel like some sort of a diagram would be very nice at this point.
-
Only a function has the property
prototype
.instance.constructor.prototype === base // return true
To get a prototype of an object, you should use the Object.getPrototypeOf method.
Object.getPrototypeOf(instance) === base // return true
-
This page should help you out:
http://joost.zeekat.nl/constructors-considered-mildly-confusing.html
In short, the ‘behind the scenes’ prototype of an instance (created via
new
) is not accessible in any way, hence why it returnsundefined
. Only the constructor (on which you’ve manually set a.prototype
property) will return anything when you try to retrieve it.
Originally posted 2013-11-09 23:21:29.