It is often said that every Javascript object has a prototype property, but I find that foo.prototype has a value only if foo is a function.
On Chrome and Firefox, obj.__proto__ has a value — is this the said prototype property? But on IE 9, it won’t work (is there some way that can?), and I thought by prototype property, that means obj.prototype should work?
I understand that Object.getPrototypeOf(obj) seems to show this prototype property, but why need a special method to get it? Why not just like person.name, which is to get the name property of the person object?
Update: by the way, obj.constructor.prototype seems to sometimes be that prototype, but sometimes not, as in the following code done with Prototypal inheritance with no constructor: (this method is in the Pro Javascript Design Patterns book by Harmes and Diaz by Apress 2008, p. 46)
var Person = {
name: 'default value',
getName: function() {
return this.name;
}
}
var reader = clone(Person);
console.log(reader.getName());
reader.name = "Ang Lee";
console.log(reader.getName());
function clone(obj) {
function F() {};
F.prototype = obj;
return new F;
}
console.log("the prototype of reader is", Object.getPrototypeOf(reader));
console.log(Object.getPrototypeOf(reader) === reader.constructor.prototype);
console.log(Object.getPrototypeOf(reader) == reader.constructor.prototype);
console.log(Object.getPrototypeOf(reader) === reader.__proto__);
console.log(Object.getPrototypeOf(reader) == reader.__proto__);
the result will show false, false, true, true for the last 4 lines.
Every JavaScript object has an internal “prototype” property, often called [[prototype]], which points to the object from which it directly inherits. This is exposed in FF and Chrome by the non-standard
__proto__property.Object.getPrototypeOfis a getter for this internal property.Every JavaScript function [object] has a property
prototype, which is initialized with an [nearly] empty object. When you create a new instance of this function by calling it as a constructor, the [[prototype]] of that new object will point to the constructor’sprototypeobject.If you get the [[prototype]] of a function (every function is an object, so it has one), it will result in the
Function.prototypeobject from which functions inherit their methods (like bind, call, apply etc). See also Why functions prototype is chained repeatedly? on that.