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.